在XlsxWriter中写入后对单元格应用格式

43 投票
4 回答
50042 浏览
提问于 2025-04-17 21:56

我在用Python的XlsxWriter库工作,最近遇到一个问题一直没能解决:

我的应用需要创建一个Xlsx文件,里面的数据要以表格的形式展示。这个表格里有一些空的单元格。

我想给一些单元格加边框,这样就能形成一个表格的网格,所以我使用了:

format6 = excelbook.add_format()
format6.set_left(1)
for y in range(24):
    excel.write(y+5, 1, None, format6)

这样就可以给那些单元格加上边框。然后,我再往表格里写数据。

因为这个表格的布局比较复杂,所以我觉得可以先把数据写进去,等所有数据都写完后,再给单元格应用格式加边框,但我找不到方法。

有没有办法在单元格写入数据后,再给它应用格式,而不丢失里面的内容呢?

提前谢谢你们。

4 个回答

6

你可以设置工作簿的默认格式:

import xlsxwriter
workbook = xlsxwriter.Workbook('example.xlsx')

# default cell format to size 10 
workbook.formats[0].set_font_size(10)
# default cell format to center
workbook.formats[0].set_align('center')
...
10

一种方法是使用一个包装方法来写入单元格,然后用一个辅助方法来覆盖单元格的值和样式。

import xlsxwriter

class XLSGenerator:
    def __init__(self):
        self.workbook = xlsxwriter.Workbook('file.xls')
        sheet1 = self.workbook.add_worksheet('sheet1')
        sheet2 = self.workbook.add_worksheet('sheet2')
        self.sheets = {'sheet1': sheet1, 'sheet2': sheet2}
        #  dictionary with all written cells
        self.written_cells = {sheet: {} for sheet in self.sheets}

    def write_cell(self, sheet_name, cell, value, cell_format_dict=None):
        """Writes value and style, and saves it in self.written_cells"""

        sheet = self.sheets[sheet_name]
        if cell_format_dict:
            cell_format = self.workbook.add_format(cell_format_dict)
            sheet.write(cell, value, cell_format)
        else:
            cell_format_dict = None
            sheet.write(cell, value)

        # save sheet_name, cell and cell_value, and cell_format (dict)
        # example ['sheet1']['C12'] = ('some_text', {'font_size': 14, 'bold': True}
        self.written_cells[sheet_name][cell] = (value, cell_format_dict)

    def apply_style(self, sheet_name, cell, cell_format_dict):
        """Apply style for any cell, with value or not. Overwrites cell with joined 
        cell_format_dict and existing format and with existing or blank value"""

        written_cell_data = self.written_cells[sheet_name].get(cell)
        if written_cell_data:
            existing_value, existing_cell_format_dict = self.written_cells[sheet_name][cell]
            updated_format = dict(existing_cell_format_dict or {}, **cell_format_dict)
        else:
            existing_value = None
            updated_format = cell_format_dict

        self.write_cell(sheet_name, cell, existing_value, updated_format)

用法如下:

generator = XLSGenerator()
generator.write_cell('sheet1', 'A1', '10')
generator.write_cell('sheet1', 'B2', '20')
generator.write_cell('sheet1', 'C3', '30')

table_borders = {"left": 1, 'right': 1, 'top': 1, 'bottom': 1}
for cell in ('A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3'):
   generator.apply_style('sheet1', cell, table_borders)

generator.workbook.close()

在这里输入图片描述

43

另一种解决方法是使用 conditional_format,并设置 type='no_errors'

worksheet.conditional_format(your_range, {'type': 'no_errors',
                                          'format': your_format})
66

我是那个模块的作者,很遗憾,这个功能现在无法实现。

这个功能是计划中的功能,而且内部有一小部分基础设施是为了支持它而准备的,但目前还不能用,我也不能确定什么时候能用。

更新:这个功能从来没有被实现,现在也不再计划了。

撰写回答