【问题标题】:Formatting Excel files in openpyxl在 openpyxl 中格式化 Excel 文件
【发布时间】:2020-03-04 10:44:54
【问题描述】:

在我的项目中,我创建 .xlsx 文件并使用 ws.append([list]) 填充数据。像这样:

for line in inf:
    current_line = line.strip().split(';')
    ws.append(current_line)

标题行也是使用 .append() 方法添加的。

接下来我需要为标题行应用一种样式(粗体字体),为整个表格应用另一种样式(每个单元格都应该有简单的边框)。

我已经尝试了不同的方法来做到这一点(主要是在 openpyxl.readthedocs.io 和 Googled 上),但它们都不适合我。

有没有办法为第一行应用样式,并为文件中的所有现有单元格应用边框?困难在于我在每行中有不同数量的列,并且行数未知(很多)。应根据最长行的宽度应用边框,如图所示。

我尝试过的一些方法:

col = ws.column_dimensions['A']
col.border =  = Border(left=Side(border_style='thin', color='FF000000'),
             right=Side(border_style='thin', color='FF000000'),
             top=Side(border_style='thin', color='FF000000'),
             bottom=Side(border_style='thin', color='FF000000')
    )

row = ws.row_dimensions[1]
row.border =  = Border(left=Side(border_style='thin', color='FF000000'),
             right=Side(border_style='thin', color='FF000000'),
             top=Side(border_style='thin', color='FF000000'),
             bottom=Side(border_style='thin', color='FF000000')
    )

这些甚至不适用于单行/列 (1/'A')。

更新: 试过这个

row = 1
for line in inf:
    curr_line = line.strip().split(';')
    n_cols = len(curr_line)
    ws.append(curr_line)
    for col in range(1, n_cols + 1):
        cell = ws.cell(row, col)
        cell.border = cell_border
        if row == 1:        # Header Style
            cell.font = Font(bold=True)
    row += 1

结果。边界分布在某种程度上并不均匀。有些行很短,有些行很长,看起来并不令人满意。除此之外,有些单元格没有边框或根本没有边框。

【问题讨论】:

  • 您能添加一些您尝试过的代码吗?
  • @Delena Malan 更新

标签: python openpyxl xlsx xls


【解决方案1】:

我假设您尝试将单元格样式应用于“list”类型,而不是“openpyxl.cell.cell.Cell”类型。

下面是sn-p在假设下使用openpyxl添加样式:

  • current_line : 一些东西的列表。
  • 标题仅为第 1 行。
  • 版本:Python 3.8.1
from openpyxl import load_workbook
from openpyxl.styles import Border, Side, Font

wb = load_workbook(filename="sample.xlsx", read_only=False)
ws = wb.active

data = [["H1", "H2", "H3", "H4", "H5", "H6"],[1,2,3,4,5,6,7],[11,12,13],[21,22,23,24,25,26,27],[31,32],[41,42,43,44,45],[51,52]]

cell_border = Border(left=Side(border_style='thin', color='FF000000'),
                     right=Side(border_style='thin', color='FF000000'),
                     top=Side(border_style='thin', color='FF000000'),
                     bottom=Side(border_style='thin', color='FF000000')
)

n_rows = len(data)
for row in range(1, n_rows + 1):
    n_cols = len(data[row-1])
    ws.append(data[row-1])
    for col in range(1, n_cols + 1):
        cell = ws.cell(row, col)
        cell.border = cell_border
        if row == 1:        # Header Style
            cell.font = Font(bold=True)
wb.save("sample.xlsx")

您可以修改以适合您的确切要求。 希望对您有所帮助。

更新:

max_rows = 0
max_cols = 0

for line in inf:
    current_line = line.strip().split(';')
    ws.append(current_line)
    max_rows += 1
    row_size = len(current_line)
    if row_size > max_cols:
        max_cols = row_size

for row in range(1, max_rows + 1):
    for col in range(1, max_cols + 1):
        cell = ws.cell(row, col)
        cell.border = cell_border
        if row == 1:        # Header Style
            cell.font = Font(bold=True)

关于openpyxl单元格格式here的更多细节。

【讨论】:

  • 问题是我不知道数据长度,因为我从文件中读取数据,它可能非常大。现在我正在尝试使您的解决方案适合我的项目,所以感谢您的建议。
  • 好的,所以我根据我的情况调整了您的解决方案。但是,不幸的是,它并没有像我希望的那样工作得那么好。我已经用您的解决方案和结果更新了问题。
  • 在我用数据填充文件后,有没有办法给所有单元格添加边框?
  • 这里的目标是使用 openpyxl lib 为 Cell 添加样式。文件的处理、逻辑流程等完全由您来完成。而且,是的,您可以在用所有数据填充文件后为所有单元格添加边框,您需要为此进行两次迭代,一次填充数据,另一个添加样式。我已经更新了答案以包含它。
  • 哦,天哪,这简直太完美了!非常感谢你!顺便说一句,它的工作速度有多快?看,我有一个 845 行的 txt 文件,其中最长的是 'Z' 列(在 Excel 中)。它执行 6-10 秒。
猜你喜欢
  • 1970-01-01
  • 2023-02-09
  • 1970-01-01
  • 2010-09-13
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多