python合并单元格出现:‘MergedCell‘ object attribute ‘value‘ is read

您所在的位置:网站首页 !only python合并单元格出现:‘MergedCell‘ object attribute ‘value‘ is read

python合并单元格出现:‘MergedCell‘ object attribute ‘value‘ is read

#python合并单元格出现:‘MergedCell‘ object attribute ‘value‘ is read| 来源: 网络整理| 查看: 265

出现这种错误一般都是在用方法:ws.merge_cells() 合并单元格后,直接给单元格赋值导致的。

经过我的不断尝试,发现在合并单元格的初始位置赋值就不会出现问题。 比如以下代码:

from openpyxl import Workbook wb = Workbook() ws = wb.active ws.merge_cells('A2:A99') ws['A2'] = 'TEST' # 给合并开头的的格子赋值,成功 wb.save("D:test.xlsx")

可正常运行,但如果将ws['A2'] = 'TEST'改为ws['A3'] = 'TEST' 便会出现异常:

AttributeError: ‘MergedCell’ object attribute ‘value’ is read-only

为啥会这样?以下是个人的推测: 阅读merge_cells源码

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) """ cr = CellRange(range_string=range_string, min_col=start_column, min_row=start_row, max_col=end_column, max_row=end_row) self.merged_cells.add(cr) self._clean_merge_range(cr)

最后调用了_clean_merge_range(cr) 查看源码:

def _clean_merge_range(self, mcr): """ Remove all but the top left-cell from a range of merged cells and recreate the lost border information. Borders are then applied """ if not isinstance(mcr, MergedCellRange): mcr = MergedCellRange(self, mcr.coord) cells = mcr.cells next(cells) # skip first cell for row, col in cells: self._cells[row, col] = MergedCell(self, row, col) mcr.format()

其中的注释有一句: Remove all but the top left-cell from a range of merged cells 从一系列合并的单元格中删除除左上单元格外的所有单元格 and recreate the lost border information. 并且重新创建丢失的边框信息 Borders are then applied 丢失的边框应用到实际 也就是说,python合并单元格的过程是先删除除开左上单元格外的单元格,接下去删除下面所有的单元格并且重建建立边框。 即除开左上的单元格可以访问之外,被删除的那些已经无法进行读写操作了。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3