简体   繁体   English

是否可以将单元格与 openpyxl 只写工作表合并?

[英]Is it possible to merge cells with an openpyxl write-only worksheet?

I am creating worksheets with about 100,000 rows and openpyxl's writing operation is quite slow.我正在创建大约 100,000 行的工作表,而 openpyxl 的写入操作非常慢。 It would be useful to get a row object and to fill it in, but I can't find an API for that.获取行对象并填充它会很有用,但我找不到相应的 API。 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.我对这种模式的问题是它显然不支持合并单元格,因为合并单元格似乎是在电子表格上完成的操作,而不是在附加的行上完成的操作。

from openpyxl import Workbook
from openpyxl.cell import WriteOnlyCell
from openpyxl.comments import Comment
from openpyxl.styles import Font
wb = Workbook(write_only = True)
ws = wb.create_sheet()
cell = WriteOnlyCell(ws, value="hello world")
cell.font = Font(name='Courier', size=36)
cell.comment = Comment(text="A comment", author="Author's Name")
ws.append([cell, 3.14, "foo","bar",None])
ws.append(["merged cells"])
ws.merge_cells(start_row=2,end_row=2,start_column=1,end_column=5)
wb.save('write_only_file.xlsx')
% python cm.py
Traceback (most recent call last):
  File "cm.py", line 12, in <module>
    ws.merge_cells(start_row=2,end_row=2,start_column=1,end_column=5)
AttributeError: 'WriteOnlyWorksheet' object has no attribute 'merge_cells'

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?否则,写入单元格的方法比使用ws.cell()获取每个单元格并手动设置它更快吗?

No, it is not possible in write-only mode to specify if cells are merged.不,在只写模式下无法指定是否合并单元格。

The information regarding merged cells is at the end of the worksheet and the API currently doesn't support this functionality, although it would probably be possible to add the code to do this.有关合并单元格的信息位于工作表的末尾,并且 API 当前不支持此功能,尽管可能可以添加代码来执行此操作。

Messing around with the merged_cells attribute of the worksheet worked for me.弄乱工作表的merged_cells属性对我merged_cells Here is an example:下面是一个例子:

from openpyxl.workbook import Workbook

wb = Workbook(write_only=True)
ws = wb.create_sheet("Test")

ws.append(['A', '', '', '', '', 'B', '', '', '', ''])

for _ in range(100):
    ws.append(['%d' % i for i in range(10)])

ws.merged_cells.ranges.append("A1:E1")
ws.merged_cells.ranges.append("F1:J1")

wb.save("Test.xlsx")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM