关于openpyxl的性能和优化
python内封装了很多强大的功能库,包括对office办公软件的许多操作,相比较于对word的操作库来说,python对excel表格的操作库要友好很多,其中广为人知的当属于pandas和openpyxl。
我在对excel表操作时注意到,对于一个较大的excel表的操作,在相同环境下使用pandas和openpyxl的运行时间是不一样的,在openpyxl官方文档中发现:
openpyxl attempts to balance functionality and performance. Where in doubt, we have focused on functionality over optimisation: performance tweaks are easier once an API has been established. Memory use is fairly high in comparison with other libraries and applications and is approximately 50 times the original file size, e.g. 2.5 GB for a 50 MB Excel file. As many use cases involve either only reading or writing files, the Optimised Modes modes mean this is less of a problem.
翻译过来就是:
openpyxl尝试平衡性能和功能。毫无疑问, 我们更关注功能的实现: 一旦API建立 性能的优化就更加容易. 与其他库和应用程序相比,openpyxl内存的使用量大约是原始文件的50倍 例如 50 MB Excel 文件的内存使用量为 2.5 GB。
那如果excel表很大,而我们又不得不使用openpyxl对excel表进行操作,应该怎么办呢?
由于许多用例只涉及读取或写入文件,使用优化模式可以很好的解决这个问题
官方文档中给出了对应的优化模式:
- 只读模式
有时,你需要打开或写入非常大的 XLSX 文件,并且 openpyxl 中的通用例程将无法处理该负载。但是,有两种模式使你能够读取和写入无限量的数据,并且内存消耗变化不大。
推荐使用 openpyxl.worksheet._read_only.ReadOnlyWorksheet:
from openpyxl import load_workbookwb = load_workbook(filename='large_file.xlsx', read_only=True)ws = wb['big_data'] for row in ws.rows: for cell in row: print(cell.value)
-
写入模式
同样,常规的openpyxl.worksheet.worksheet.Worksheet方法已经被更快的 openpyxl.worksheet._write_only.WriteOnlyWorksheet方法代替。当你想操作大量数据时,请确保你已经安装 lxml库
>>> from openpyxl import Workbook>>> wb = Workbook(write_only=True)>>> ws = wb.create_sheet()>>>>>> # now we'll fill it with 100 rows x 200 columns>>>>>> for irow in range(100):... ws.append(['%d' % i for i in range(200)])>>> # 保存文件>>> wb.save('new_big_file.xlsx') # doctest: +SKIP
如果想使写入的单元格具有样式或者注释,请使openpyxl.cell.WriteOnlyCell()方法
>>> from openpyxl import Workbook>>> wb = Workbook(write_only = True)>>> ws = wb.create_sheet()>>> from openpyxl.cell import WriteOnlyCell>>> from openpyxl.comments import Comment>>> from openpyxl.styles import Font>>> 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, None])>>> wb.save('write_only_file.xlsx')
这将创建一个仅允许写入(write-only)的工作簿(workbook), 并且添加一行,这行仅包含三个单元格: 一个带有自定义字体和注释的文本单元格,一个浮点数, 和一个空单元格 (无论如何都会被丢弃)。
警告:
- 与普通工作簿不同,新创建的仅写(write-only)工作簿不包含任何工作表; 工作表必须使用 create_sheet()方法专门创建。
- 在仅允许写入(write-only)的工作簿中,只能用 append(). 添加行。不能用 cell() 或 iter_rows()在任意位置写入 (或读取) 单元格。
- 它能够导出近乎无限数量的数据 (甚至超过 Excel 实际处理的数据),同时将内存使用量保持在 10Mb 以下。
- 仅写(write-only)工作簿只能保存一次。之后,每次尝试将工作簿或 append () 保存到现有工作表时,都会引发openpyxl.utils.exceptions.WorkbookAlreadySaved 异常。
- Everything that appears in the file before the actual cell data must be created before cells are added because it must written to the file before then. For example, freeze_panes should be set before cells are added.