简体   繁体   English

在 openpyxl 中格式化 Excel 文件

[英]Formatting Excel files in openpyxl

In my project I create .xlsx file and fill it with data using ws.append([list]).在我的项目中,我创建了 .xlsx 文件并使用 ws.append([list]) 用数据填充它。 Like that:像那样:

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

Header row is also added using .append() method.还使用 .append() 方法添加标题行。

The next thing I need to do is to apply one style for a header row (bold font), and another style for the entire table (each cell should have simple borders).我需要做的下一件事是为标题行应用一种样式(粗体),为整个表格应用另一种样式(每个单元格应该有简单的边框)。

I have tried different methods to do so (primarily on openpyxl.readthedocs.io, and Googled), but none of them worked for me.我尝试了不同的方法来做到这一点(主要是在 openpyxl.readthedocs.io 和谷歌上),但没有一个对我有用。

Is there a way to apply style for the first row, and apply borders for all of the existing cells in the file?有没有办法为第一行应用样式,并为文件中的所有现有单元格应用边框? The difficulty is that I have different amount of columns in each row, and unknown amount of rows (a lot of them).困难在于我在每行中有不同数量的列,以及未知数量的行(很多)。 The borders should be applied accordingly to the width of the longest row, like at the pic.边框应相应地应用于最长行的宽度,如图片所示。

在此处输入图片说明

Some of the methods I tried:我试过的一些方法:

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')
    )

These don't even work for a single row/column (1/'A').这些甚至不适用于单行/列(1/'A')。

UPD: tried this UPD:试过这个

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

The result of that.那样的结果。 The border distribution is somehow not uniform.边界分布不知何故不均匀。 Some rows are short, some are long, and it looks not satisfying.有些行很短,有些行很长,看起来并不令人满意。 Besides that, some cells don't have one of the borders or don't have them at all.除此之外,有些单元格没有边界之一或根本没有边界。 在此处输入图片说明

I assume you are trying to apply Cell Style to ' list ' type, rather than ' openpyxl.cell.cell.Cell ' type.我假设您正在尝试将单元格样式应用于“列表”类型,而不是“ openpyxl.cell.cell.Cell ”类型。

Below is the snippet to add styles using openpyxl under assumptions:以下是在假设下使用openpyxl添加样式的代码段:

  • current_line : List of something. current_line :某物的列表。
  • Header is Row 1 only.标题仅为第 1 行。
  • version: Python 3.8.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")

You can modify to suit your exact requirement.您可以修改以满足您的确切要求。 Hope it helps.希望能帮助到你。

Update:更新:

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)

More details on openpyxl cell formatting here .有关openpyxl单元格格式的更多详细信息,请访问此处

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM