如何设置整张工作表的背景颜色?

问题描述 投票:0回答:2

我想为整个工作表设置相同的背景颜色和单元格边框颜色。

我无法在任何地方找到适用于整张纸的解决方案。

python python-3.x openpyxl
2个回答
1
投票

正如 @Gino Mempin 所说,Openpyxl 适用于单元格,因此您需要为工作表中的所有单元格设置背景。然后,您可能更愿意只更改一系列单元格而不是整个工作表。
最好使用 iter_rows 来使用内存。
该示例填充 1000 行和列。一张工作表的最大尺寸可能高达 1,048,576 行 x 16,384 列,完成整个工作表可能需要一些时间。我不知道 Openpyxl 是否提供总限制作为在代码中使用的值,但需要它们的情况并不常见,因此您可能需要输入固定值。如前所述,您可能只想更改一个范围,例如

涵盖的“已使用范围”
ws.max_row
ws.max_column 

此示例将单元格颜色更改为红色...

from openpyxl import load_workbook
from openpyxl.styles import PatternFill

filename = 'foo.xlsx'

wb = load_workbook(filename)
ws = wb['Sheet1']

for row in ws.iter_rows(max_row=1000, max_col=1000):
    for cell in row:
        print(cell)
        cell.fill = PatternFill("solid", fgColor="FF0000")

wb.save(filename)

1
投票

可以通过编辑工作簿的默认值来编辑整个工作表的默认背景和边框,但我不知道它有多合法:

使用 Openpyxl
(可以在Linux以及Windows和MAC上运行)

import openpyxl
from openpyxl import Workbook
from openpyxl.styles import PatternFill
from openpyxl.styles.borders import Border, Side

wb = Workbook()

# Add a patternfill solid white (this hide the usual grid around a cell)
j = wb._fills.add(PatternFill("solid",start_color="FFFFFFFF"))

# Add a thick border to all sides style
k = wb._borders.add(Border(left=Side(style='thick'), 
    right=Side(style='thick'), 
    top=Side(style='thick'), 
    bottom=Side(style='thick')))

# Update the default style with the new values
wb._cell_styles[0] = openpyxl.styles.cell_style.StyleArray([0, j, k, 0, 0, 0, 0, 0, 0])

此代码用于使用 Xlwings 设置背景。
Xlwings 需要 Excel 才能工作,因此也依赖于 Windows 或 MAC 操作系统,但可以轻松设置整个工作表颜色。

import xlwings as xw


filename = "foo.xlsx"

red = (255, 0, 0)

with xw.App() as app:
    wb = xw.Book(filename)
    ws = wb.sheets['Sheet1']

    ### Any one of the following will set the whole sheet to a red background
    ws.api.Cells.Interior.ColorIndex = 3
    # ws.api.Cells.Interior.Color = rgb_to_int(red)
    # ws.api.Cells.Interior.Color = '&H0000FF'

    ### Cell Border color can also be set with Color or ColorIndex same as background colormax_row=1000, max_col=1000):
    ### Also the weight and style with the following 
    ws['A1'].api.Borders.ColorIndex = 3:
    # ws['A1'].api.Borders.Color = '&H0000FF' # or use rgb_to_int(red)
    ws['A1'].api.Borders.Weight = 3
    ws['A1'].api.Borders.LineStyle = 1

    wb.save(filename)
© www.soinside.com 2019 - 2024. All rights reserved.