Python 使用openpyxl以优化的方式编辑XLSX样式
我知道不可能在优化写入中定义样式,但是有没有办法写入标题定义样式,然后将优化写入设置为true以写入其余数据? 像这样的Python 使用openpyxl以优化的方式编辑XLSX样式,python,python-2.7,openpyxl,Python,Python 2.7,Openpyxl,我知道不可能在优化写入中定义样式,但是有没有办法写入标题定义样式,然后将优化写入设置为true以写入其余数据? 像这样的 wb = Workbook(encoding="utf-8") ws = wb.create_sheet() #change styles and write header wb.optimized_write=True #write rest of data 简短的回答是不,不是直接的 更长的答案是,您必须更新openpyxl.writer.dump_工作表.ExcelD
wb = Workbook(encoding="utf-8")
ws = wb.create_sheet()
#change styles and write header
wb.optimized_write=True
#write rest of data
简短的回答是不,不是直接的 更长的答案是,您必须更新openpyxl.writer.dump_工作表.ExcelDumpWriter和openpyxl.writer.dump_工作表.DumpWorksheet 查看DumpWorksheet是如何使用DumpWorksheet.append写入行的,其中有两种预设样式之一用于设置datetime单元格的样式
# Example on how you would use this
from openpyxl.writer.dump_worksheet import ExcelDumpWriter, DumpWorksheet
from openpyxl.writer.styles import StyleWriter
wb.optimized_worksheet_class=MyDumpWorksheet
my_header_style = Style()
my_header_style.font.bold = True
writer = ExcelDumpWriter(workbook)
writer.style_writer._style_list.append(my_header_style)
writer.save(filename)
# A start on how you would overload DumpWorksheet.append()
class MyDumpWorksheet(DumpWorksheet):
def __init__(self, parent_workbook, title):
DumpWorksheet.__init__(self, parent_workbook, title)
def append(self, row):
"""Overload to write the correct styles"""
# .... keep the initial setup before this
attrs = {'r': '%d' % row_idx,
'spans': '1:%d' % span}
start_tag(doc, 'row', attrs)
if row == 1:
# Assuming cell is a string here --
for col_idx, cell in enumerate(row):
if cell is None:
continue
coordinate = '%s%d' % (get_column_letter(col_idx + 1), row_idx)
attributes = {'r': coordinate}
# Assuming string!!
cell = self._string_builder.add(cell)
# 2 here refers to the style you added to writer.style_writer._style_list.
attributes['t'] = {'type':Cell.TYPE_STRING, 'style':'2'}
start_tag(doc, 'c', attributes)
tag(doc, 'v', body='%s' % cell)
end_tag(doc, 'c')
end_tag(doc, 'row')
else:
# Keep to the original append() logic
现在可以在只写模式下使用样式。要做到这一点,您需要使用WriteOnlyCell,并将其包含在传递给工作表的任何iterable中。标题是工作表的第一行吗?是的,确实是。它是第一行,也是工作表中的第一行。