我正在学习使用openpyxl模块,并且试图在工作表中创建标准样式。我一直在寻找文档和其他人的问题的答案,但找不到。
我已经找到了更改单个单元格样式的方法,并且可以将其循环应用于大量单元格,但这并不能解决我的问题,因为我需要整张纸都适合这种样式。
所以我的问题是,是否有可能做到这一点,以及如何做到。
谢谢。
我已经阅读了本文档,但未回答以下问题:https://openpyxl.readthedocs.io/en/stable/styles.html
from openpyxl.styles import NamedStyle, Font, Border, Side
import openpyxl
workbook = openpyxl.Workbook()
highlight = NamedStyle(name = "highlight")
highlight.font = Font(bold=True, size=20)
bd = Side(style='thick', color="000000")
highlight.border = Border(left=bd, top=bd, right=bd, bottom=bd)
sheet = workbook.get_sheet_by_name('Sheet')
sheet['A1'].style = highlight
workbook.save('example.xlsx')
在此示例中,我可以为单个单元格设置格式,但需要将其应用于整个工作表中。
答案 0 :(得分:0)
虽然您可以更改Normal
样式,但这可能不是最佳方法。最好创建样式并将其应用于工作表中的每个单元格。实际上,这可以很快避免任何不良的副作用。
答案 1 :(得分:0)
使用:
import openpyxl
from openpyxl.styles import NamedStyle
standard_var = NamedStyle(
name="thounsed_sep",
number_format='#,###'
)
filename = r"test.xlsx"
wb = openpyxl.load_workbook(filename)
wb.add_named_style(standard_var)
for ws in wb.worksheets:
for cells in ws.rows:
for cell in cells:
cell.style = "thounsed_sep"
wb.save()
这会更改每张纸使用范围的格式(即,用任何文本或数字内容填充的范围)。
答案 2 :(得分:0)
您可以通过sheet.dimensions
获取当前的整个工作表范围:
sheet[ sheet.dimensions ].style = highlight