openpyxl在更改单元格后破坏文件格式

2021-04-11 19:09:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我的一些格式有点奇怪。在

模板如下所示: Correct formattig

更改任何单元格中的值后,格式将被破坏,图像将消失: enter image description here

更改单元格的代码如下所示:

wb2 = load_workbook('template.xlsx')
ws2 = wb2.active

ws2['A1'] = user.name

wb2.save('template.xlsx')

标准的东西,但有些东西不对劲。我应该使用另一个模块而不是openpyxl吗?在

1条回答
网友
1楼 ·

这是一个已知的bug,在OpenPyXL的BitBucket问题列表中被标记为已解决。但是,它仍然不起作用,您必须使用由kseehart/db2053提出的补丁与Issue #365。在

我在这里为你复制了补丁:
免责声明:我没有创建这个,它是kseehart/db2053提出的解决方案)

def patch_worksheet():
"""This monkeypatches Worksheet.merge_cells to remove cell deletion bug
https://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-working
Thank you to Sergey Pikhovkin for the fix
"""

    def merge_cells(self, range_string=None, start_row=None, start_column=None, end_row=None, end_column=None):
        """ Set merge on a cell range.  Range is a cell range (e.g. A1:E1)
        This is monkeypatched to remove cell deletion bug
        https://bitbucket.org/openpyxl/openpyxl/issues/365/styling-merged-cells-isnt-working
        """
        if not range_string and not all((start_row, start_column, end_row, end_column)):
            msg = "You have to provide a value either for 'coordinate' or for\
            'start_row', 'start_column', 'end_row' *and* 'end_column'"
            raise ValueError(msg)
        elif not range_string:
            range_string = '%s%s:%s%s' % (get_column_letter(start_column),
                                      start_row,
                                      get_column_letter(end_column),
                                      end_row)
        elif ":" not in range_string:
            if COORD_RE.match(range_string):
                return  # Single cell, do nothing
            raise ValueError("Range must be a cell range (e.g. A1:E1)")
        else:
            range_string = range_string.replace('$', '')

        if range_string not in self.merged_cells:
            self.merged_cells.add(range_string)


        # The following is removed by this monkeypatch:

        # min_col, min_row, max_col, max_row = range_boundaries(range_string)
        # rows = range(min_row, max_row+1)
        # cols = range(min_col, max_col+1)
        # cells = product(rows, cols)

        # all but the top-left cell are removed
        #for c in islice(cells, 1, None):
            #if c in self._cells:
                #del self._cells[c]

    # Apply monkey patch
    worksheet.Worksheet.merge_cells = merge_cells

patch_worksheet()

相关问题