简体   繁体   中英

openpyxl ruins files formatting after changing cells

I have some weird formatting for my .xlsx formatting (template for UPO).

The template looks like this: 正确格式

After changing value in any cell, the formatting is ruined, the image disappears: 在此处输入图片说明

The code that changes the cell looks like this:

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

ws2['A1'] = user.name

wb2.save('template.xlsx')

Standard stuff, but something isn't right. Should I just use another module instead of openpyxl?

This is a known bug which is marked as resolved on OpenPyXL's BitBucket Issues list. However, it is still not working and you have to use the patch proposed by kseehart/db2053 with Issue #365 .

I copied the patch for you here:
( DISCLAIMER: I did not create this, it was proposed as a solution by 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM