我有一个 Excel 文件,其中包含大约 400 个工作表,其中 375 个工作表需要保存为 CSV 文件。我尝试过 VBA 解决方案,但 Excel 在打开此工作簿时遇到问题。
我创建了一个 python 脚本来做到这一点。然而,它会迅速消耗所有可用内存,并且在导出 25 张后几乎停止工作。有人对我如何改进这段代码有建议吗?
import openpyxl
import csv
import time
print(time.ctime())
importedfile = openpyxl.load_workbook(filename = "C:/Users/User/Desktop/Giant Workbook.xlsm", data_only = True, keep_vba = False)
tabnames = importedfile.get_sheet_names()
substring = "Keyword"
for num in tabnames:
if num.find(substring) > -1:
sheet=importedfile.get_sheet_by_name(num)
name = "C:/Users/User/Desktop/Test/" + num + ".csv"
with open(name, 'w', newline='') as file:
savefile = csv.writer(file)
for i in sheet.rows:
savefile.writerow([cell.value for cell in i])
file.close()
print(time.ctime())
任何帮助,将不胜感激。
Thanks
编辑:我正在使用 Windows 7 和 python 3.4.3。我也愿意接受 R、VBA 或 SPSS 中的解决方案。
尝试使用read_only=True
财产为load_workbook()
类,这会导致您的工作表成为IterableWorksheet
,这意味着您只能迭代它们:您不能直接使用列/行号来访问其中的单元格值。这将提供near constant memory consumption
根据文档 http://openpyxl.readthedocs.org/en/latest/optimized.html .
另外,您不需要关闭file
; the with
声明会为你处理这个问题。
例子 -
import openpyxl
import csv
import time
print(time.ctime())
importedfile = openpyxl.load_workbook(filename = "C:/Users/User/Desktop/Giant Workbook.xlsm", read_only = True, keep_vba = False)
tabnames = importedfile.get_sheet_names()
substring = "Keyword"
for num in tabnames:
if num.find(substring) > -1:
sheet=importedfile.get_sheet_by_name(num)
name = "C:/Users/User/Desktop/Test/" + num + ".csv"
with open(name, 'w', newline='') as file:
savefile = csv.writer(file)
for i in sheet.rows:
savefile.writerow([cell.value for cell in i])
print(time.ctime())
From 文档 http://openpyxl.readthedocs.org/en/latest/optimized.html -
有时,您需要打开或写入非常大的 XLSX 文件,而 openpyxl 中的常见例程将无法处理该负载。幸运的是,有两种模式使您能够以(接近)恒定的内存消耗读取和写入无限量的数据。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)