当前位置 博文首页 > 浅谈openpyxl库,遇到批量合并单元格的问题

    浅谈openpyxl库,遇到批量合并单元格的问题

    作者:刺骨寒风刺 时间:2021-05-23 18:29

    我就废话不多说了,大家还是直接看代码吧~

    from openpyxl import Workbook
    from openpyxl import load_workbook
    from openpyxl.styles import NamedStyle, Border, Side, Alignment 
     
    # 创建一个工作薄
    wb = Workbook()
     
    # 创建一个工作表(注意是一个属性)
    table = wb.active
     
    # excel创建的工作表名默认为sheet1,一下代码实现了给新创建的工作表创建一个新的名字
    table.title = 'test'
     
    # 合并C1 D1 
    # 法一
    # table.merge_cells('C1:D1')
    # table.cell(row = 1,column = 3,value = 'pdf/mp3链接')
    # 法二
    table.merge_cells(start_row=1, start_column=3, end_row=1, end_column=4)
    table.cell(1, 3).value = '合并2个单元格'
    # 法一不适合批量添加
    for i in range(2,10):
     table.merge_cells(start_row=i, start_column=3, end_row=i, end_column=4)

    效果如下:

    补充: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.
    ........................ 

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持站长博客。如有错误或未考虑完全的地方,望不吝赐教。

    js
    下一篇:没有了