使用 openpyxl 格式化的电子表格中的文本未格式化以更正 Excel 中的颜色(在 libreoffice calc 中正确显示)

Text in spreadsheet formatted using openpyxl not formatted to correct colour in Excel (shows correctly in libreoffice calc)

我已经编写了一个 python 脚本来将 Excel 传播sheet 格式化为注册 sheet。

我遇到的问题是,虽然生成的 excel sheet 在 libreoffice calc 中看起来不错,但当它在 Excel 中打开时,标题文本在黑色背景上是黑色的它应该是黑底白字。

这是代码:

#!/usr/bin/python

# Import

from openpyxl.styles import Font, PatternFill, Side, Border, Alignment
from openpyxl import load_workbook
import sys
import datetime

# Variables

file = sys.argv[1]
title = sys.argv[2]
headings = ["Etternavn", "Fornavn", "Signatur"]
date = datetime.datetime.now().strftime("%Y%m%d")

# Load workbook

wb = load_workbook(filename=file)
ws = wb.active

# Delete extra columns

ws.delete_cols(3, amount=31)

# Merge top three cells

ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=3)

# ws.cell(row=1, column=1).alignment = Alignment(horizontal="left")

# Add correct headings

for i in range(1, 4):
    cell_ref = ws.cell(row=2, column=i)
    cell_ref.value = headings[i - 1]

# Add name to top of spreadsheet

ws.cell(row=1, column=1).value = title
ws.cell(row=1, column=1).font = Font(size=16, bold=True, name='Calibri')

# Set colour, size and background colour for headers

def set_header(col_range):
    for col1 in range(1, col_range + 1):
        cell_header = ws.cell(2, col1)
        cell_header.fill = PatternFill(start_color='000000',
                                       end_color='000000',
                                       fill_type="solid")  # used hex code for red color
        cell_header.font = Font(color="FFFFFF", size=16, bold=True, name='Calibri')


set_header(ws.max_column)

# Set borders for cells

def set_border(wsa, cell_range):
    thin = Side(border_style="thin", color="000000")
    for row1 in wsa[cell_range]:
        for cell in row1:
            cell.border = Border(top=thin, left=thin, right=thin, bottom=thin)


set_border(ws, 'A1:C144')

# Set column width

for col in ['A', 'B']:
    ws.column_dimensions[col].width = 25

ws.column_dimensions['C'].width = 35

# Set row height

for row in range(1, 145):
    ws.row_dimensions[row].height = 30

# Variables for alignment

rows = range(1, 144)
rows2 = range(2, 145)
columns = range(1, 10)


# Set vertical alignment

def set_vert_align(vrows, vcolumns):
    for row2 in vrows:
        for col2 in vcolumns:
            ws.cell(row2, col2).alignment = Alignment(vertical='center', wrap_text=True)


set_vert_align(rows, columns)


# Set font size for names

def set_row_size_font(frows, fcolumns):
    for row3 in frows:
        for col3 in fcolumns:
            ws.cell(row3, col3).font = Font(size=13, name='Calibri')


set_row_size_font(rows2, columns)

# Save Excel spreadsheet

wb.save(date + " " + title + ".xlsx")

字体颜色错误的原因是你在最后覆盖了字体......就在保存之前 - 在这一行set_row_size_font(rows2, columns)

如果您评论该行,它将正常工作。您需要更改 rows2 以排除第二行或创建另一个变量