更改单元格后,openpyxl会废弃文件格式

时间:2018-02-06 22:55:35

标签: python openpyxl

我的.xlsx格式(UPO模板)有一些奇怪的格式。

模板如下所示: Correct formattig

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

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

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

ws2['A1'] = user.name

wb2.save('template.xlsx')

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

1 个答案:

答案 0 :(得分:1)

这是一个已知错误,在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()