【发布时间】:2015-09-20 06:53:36
【问题描述】:
我有一个 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())
任何帮助将不胜感激。
谢谢
编辑:我使用的是 Windows 7 和 python 3.4.3。我也对 R、VBA 或 SPSS 中的解决方案持开放态度。
【问题讨论】:
-
在 with 块之后不需要 file.close()