我一直在阅读与openpyxl合并单元格时解决excel边框问题有关的所有材料。我的问题是我试图从bucketlist中实现并在此处其他帖子中提到的monkeypatch解决方案,但是在运行该解决方案时,我总是收到错误消息。
AttributeError:“工作表”对象没有属性“ _merged_cells”
有人能指出我正确的方向吗?
from itertools import product
import types
import openpyxl
from openpyxl import worksheet
from openpyxl.utils import range_boundaries
from openpyxl import Workbook
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.append(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
m = types.MethodType(merge_cells, None, worksheet.Worksheet)
worksheet.Worksheet.merge_cells = m
wb = Workbook()
ws = wb.create_sheet('Mysheet')
patch_worksheet()
ws.merge_cells('A21:C21')
test_cell = ws['A21']
test_cell.value = 'My comment'
test_cell.border = Border(top=medium, left=medium, right=medium, bottom=medium)
test_cell.font = Font(b=True, color='000000')
test_cell.alignment = Alignment(horizontal='center', vertical='center')
wb.save('test.xlsx')