原excel有合并单元格这种格式,openpyxl打开然后保存边框消失的问题

python3.5 openpyxl2.5可以用这个文件解决

文件名为:fix_border.py,代码见下面的代码片

在你写代码的那个文件里导入该文件
from fix_border import patch_worksheet
然后在load文件前加上patch_worksheet()
全部代码为

    ws = opx.load_workbook(filename1)
     fix_border.patch_worksheet()
    ws.save(filename2)

fix_border.py代码为

# -*- coding:utf-8 -*-
from itertools import product
import types
import openpyxl
from openpyxl.utils import get_column_letter
from openpyxl import worksheet
from openpyxl.utils import range_boundaries
from itertools import product
import regex as re
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()

openpyxl 删除行操作,合并单元格格式混乱的问题

openpyxl在采取删除行操作后,即sheet.delete_rows(row,1),即便使用了上面的patch_worksheet,但是还是不能解决这个单元格格式混乱的情况,目前没有找到解决的方案。

##更新—openpyxl格式混乱问题解决方案2
见链接
https://bitbucket.org/openpyxl/openpyxl/issues/700/cell-borders-lost-on-save
https://bitbucket.org/openpyxl/openpyxl/issues/700/cell-borders-lost-on-save