如何使用python更快地复制和粘贴大型excel文件(27MB) ?



使用此代码时,将数据从一个excel工作表(27k行和100列)复制并粘贴到另一个excel文件的特定工作表需要花费数小时。有没有更好的方法来加快这个过程?

import openpyxl as xl;
filename ="C:\Users\livin.vincent\OneDrive - Automation Anywhere\Desktop\New folder\New Microsoft Excel.xlsx"
wb1 = xl.load_workbook(filename)
ws1 = wb1.worksheets[0]
filename1 ="C:\Users\livin.vincent\OneDrive - Automation Anywhere\Desktop\New folder\New Microsoft Excel Worksheet.xlsx"
wb2 = xl.load_workbook(filename1)
ws2 = wb2.worksheets[0]
mr = ws1.max_row
mc = ws1.max_column
for i in range (1, mr + 1):
for j in range (1, mc + 1):
c = ws1.cell(row = i, column = j)
ws2.cell(row = i, column = j).value = c.value
wb2.save(str(filename1))

如果只是原始文件复制(如Mark Setchell建议)不是一个选项,您可以通过将源工作簿打开为只读并使用iter_rows:

来加快速度。
source_wb = openpyxl.load_workbook("test.xlsx", read_only=True)
dest_wb = openpyxl.load_workbook("test2.xlsx")
source_ws = source_wb.worksheets[0]
dest_ws = dest_wb.worksheets[0]
for y, row in enumerate(source_ws.iter_rows(values_only=True), 1):
for x, value in enumerate(row, 1):
dest_ws.cell(y, x).value = value

对于500x500单元格的工作簿,这似乎快了大约20%(包括文件IO时间)。

更多的性能?!

如果您愿意更深入地研究openpyxl的内部结构,这似乎还能提供更多的性能(比原来快25%,分析器告诉我大部分时间都花在解析XML上)

注意,我只对数字进行了尝试,所以它可以很好地处理奇怪的事情,例如日期(但我们已经习惯Excel这样做了,不是吗…)。

def fast_readonly_ws_parse(ws: ReadOnlyWorksheet):
with contextlib.closing(ws._get_source()) as src:
parser = WorkSheetParser(
src,
ws._shared_strings,
data_only=True,
epoch=ws.parent.epoch,
date_formats=ws.parent._date_formats,
)
for idx, row in parser.parse():
yield (idx, [cell['value'] for cell in row])
# ...
source_wb = openpyxl.load_workbook("test.xlsx", read_only=True)
dest_wb = openpyxl.load_workbook("test2.xlsx")
source_ws = source_wb.worksheets[0]
dest_ws = dest_wb.worksheets[0]
for y, row in fast_readonly_ws_parse(source_ws):
for x, value in enumerate(row, 1):
dest_ws.cell(y, x).value = value

最新更新