I am creating worksheets with about 100,000 rows and openpyxl’s writing operation is quite slow. It would be useful to get a row object and to fill it in, but I can’t find an API for that. The documentation on optimization mentions write-only mode. My problem with this mode is that it doesn’t obviously support merged cells, because merging cells seems to be an operation that is done on a spreadsheet, not on a row that is appended.
JavaScript
x
14
14
1
from openpyxl import Workbook
2
from openpyxl.cell import WriteOnlyCell
3
from openpyxl.comments import Comment
4
from openpyxl.styles import Font
5
wb = Workbook(write_only = True)
6
ws = wb.create_sheet()
7
cell = WriteOnlyCell(ws, value="hello world")
8
cell.font = Font(name='Courier', size=36)
9
cell.comment = Comment(text="A comment", author="Author's Name")
10
ws.append([cell, 3.14, "foo","bar",None])
11
ws.append(["merged cells"])
12
ws.merge_cells(start_row=2,end_row=2,start_column=1,end_column=5)
13
wb.save('write_only_file.xlsx')
14
JavaScript
1
6
1
% python cm.py
2
Traceback (most recent call last):
3
File "cm.py", line 12, in <module>
4
ws.merge_cells(start_row=2,end_row=2,start_column=1,end_column=5)
5
AttributeError: 'WriteOnlyWorksheet' object has no attribute 'merge_cells'
6
Is there any way to support merging cells? Failing that, what’s a faster way to write cells than to get each cell with ws.cell()
and manually set it?
Advertisement
Answer
Messing around with the merged_cells
attribute of the worksheet worked for me. Here is an example:
JavaScript
1
15
15
1
from openpyxl.workbook import Workbook
2
3
wb = Workbook(write_only=True)
4
ws = wb.create_sheet("Test")
5
6
ws.append(['A', '', '', '', '', 'B', '', '', '', ''])
7
8
for _ in range(100):
9
ws.append(['%d' % i for i in range(10)])
10
11
ws.merged_cells.ranges.append("A1:E1")
12
ws.merged_cells.ranges.append("F1:J1")
13
14
wb.save("Test.xlsx")
15