我有一个包含大约 400 个工作表的 Excel 文件,我需要将其中的 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())
如有任何帮助,我们将不胜感激。
谢谢
编辑:我使用的是 Windows 7 和 Python 3.4.3。我也愿意接受 R、VBA 或 SPSS 中的解决方案。
最佳答案
尝试为 load_workbook()
类使用 read_only=True
属性,这会使您获得的工作表成为 IterableWorksheet
,这意味着您可以仅遍历它们:您不能直接使用列/行号来访问其中的单元格值。根据 documentation,这将提供 接近恒定的内存消耗
.
此外,您不需要关闭文件
; 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())
来自 Documentation -
Sometimes, you will need to open or write extremely large XLSX files, and the common routines in openpyxl won’t be able to handle that load. Fortunately, there are two modes that enable you to read and write unlimited amounts of data with (near) constant memory consumption.
关于 python : Reading Large Excel Worksheets using Openpyxl,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31189727/