python操作excel --openpyxl里的关于merge的一些bug

开始新的工作不久,工作内容依然是数据相关

新工作数据输出模式是用excel,大概是每天导出新数据并用excel体现,同时要保留之前的数据。

我来之前,同时写好了许多sql,然后就从Navicat里面复制粘贴到excel中。

我目前在做关于这个的自动化脚本,使用的库是openpyxl,下面说说关于这个的几个小bug。

1- 在 2.5.x版本中,当你合并单元格的时候

使用的是merge_cells(),然后,当你合并多个单元格的时候,之前合并的单元格的边框会消失。这个问题我再官网找到解决方案,稍有复杂,但是只要你更新到2.6.x版本,这个问题自动解决。

2- 2.6x版本中,使用unmerge_cell() 解开合并单元格后,除了左上角可以写入,其他被解开的单元格无法写入,会提示说 ‘read_only’这类的。

例如:你的 ("A1:D4") 是合并的,当你使用 work_sheet.unmerge_cell("A1:D4")后,会解开合并,

然后你却只能给A1赋值,不能给A2,A3,A4,B1....赋值,提示如下

 === >  - Openpyxl ['MergedCell' object attribute 'hyperlink' is read-only] 

我尝试改用delete直接删除,然而这种方法只能删除内容,格式还是被锁定的。

找了很久没有结局方法,只好慢慢看源码。

大概是说,接触合并后,代码默认其他单元格应该是空值且不能被赋新值,也许是因为觉得解开只有要再合并??(不明白设疑初衷)

处理方法如下,大概思想是格式化该单元格的属性,即取消的read_only属性。

大概在源码的中workshet.py文件的大约620做添加如下代码:(# autho...开始,大家自己对照源码添加吧~~~)

........................ 
     if cr.coord not in self.merged_cells:
            raise ValueError("Cell range {0} is not merged".format(cr.coord))

        self.merged_cells.remove(cr)

        # Deletes the MergedCellRange.
        # del self._merged_cell_range[cr.bounds]
        # autho     : watson
        # aim       : deal with the bug about umerger
        # describe  : Add the following five lines of code to format the attribute.
        min_col, min_row, max_col, max_row = cr.bounds
        for row in range(min_row, max_row + 1):
            for col in range(min_col, max_col + 1):
                if col == min_col and row == min_row:
                    continue
                del self._cells[(row, col)]


    def append(self, iterable):
        """Appends a group of values at the bottom of the current sheet.
........................ 
发布了14 篇原创文章 · 获赞 12 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/Watson_Ashin/article/details/88862388