【问题标题】:Apply format to a cell after being written in XlsxWriter在 XlsxWriter 中写入后将格式应用于单元格
【发布时间】:2014-04-16 16:03:54
【问题描述】:

我使用 XlsxWriter 在 python 上工作,我一直在尝试解决这个问题,但没有成功:

我的应用程序必须创建一个 Xlsx 文件,其中数据以类似表格的结构显示。 该表有一些空单元格。

我想为一些单元格设置边框来为表格创建一个网格,所以我使用:

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

为了将边框应用于这些单元格。然后,我在表格上写数据。

由于表格布局相当复杂,写数据会很容易,写完所有内容后,将格式应用于单元格以具有边框,但我找不到方法。

有什么方法可以在单元格之前写入后将格式应用于单元格而不丢失其内容?

提前谢谢你。

【问题讨论】:

  • documentation看,这似乎是不可能的。
  • 明确一点,您仍然可以创建您想要的最终结果;它只需要你构建你的程序逻辑,这样你就已经知道在编写每个单元格时要应用什么格式。 (您可能已经意识到这一点,但我不希望任何阅读本文的人看到“这是不可能的”字样并错误地认为这意味着他们无法解决它。)
  • 谢谢你的建议,@John,我今天已经这样做了,当然就是这样:我没有在工作表上写入来自数据库的数据,而是设法将其存储在变量,然后检查给定单元格是否必须用数据写入或只是空白才能构建布局。

标签: python excel xlsxwriter


【解决方案1】:

我是该模块的作者,不幸的是这是不可能的。

它是一个planned feature,并且(一小部分)内部基础架构可以支持它,但它目前不可用,我不能说它何时可用。

更新:此功能从未实现,也不再计划。

【讨论】:

【解决方案2】:

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

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')
...

【讨论】:

  • 我不推荐这种解决方法,因为它可能会产生一些意想不到的后果,例如影响插入工作表的图像的大小。
  • 喜欢你的回答~
【解决方案3】:

另一种解决方法是使用conditional_format,然后使用type='no_errors'

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

【讨论】:

  • 虽然这将规避许多用例的问题,但我想提请注意here 解决的一些限制:在 Excel 中,条件格式叠加在现有的单元格格式上并且并非所有单元格格式属性都可以修改。 在条件格式中不能修改的属性有字体名称、字体大小、上标和下标、对角线边框、所有对齐属性和所有保护属性.
  • 漂亮的原贴和回复
【解决方案4】:

这样做的一种方法 - 使用一种包装方法来编写单元格,并使用辅助方法来覆盖单元格的值和样式

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()

【讨论】:

    猜你喜欢
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-23
    • 2017-02-16
    • 2013-09-08
    • 1970-01-01
    相关资源
    最近更新 更多