使用openpyxl编辑优化书写的XLSX样式

时间:2013-12-20 10:10:53

标签: 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

2 个答案:

答案 0 :(得分:0)

简短的回答是否定的,不是直接回答。

更长的答案是,您需要更新openpyxl.writer.dump_worksheet.ExcelDumpWriteropenpyxl.writer.dump_worksheet.DumpWorksheet

查看DumpWorksheet如何使用DumpWorksheet.append()写入行,并使用两种预设样式之一(它设置日期时间单元格的样式)。

# 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

答案 1 :(得分:0)

现在可以在只写模式下使用样式。要执行此操作,请使用WriteOnlyCell并将其包含在您传递到工作表append()的任何可迭代中。