python : Reading Large Excel Worksheets using Openpyxl

标签 python excel csv

我有一个包含大约 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/

相关文章:

python - 类型错误 : detail() missing 1 required positional argument: 'request'

python - 通过python分割一个大的csv文件

c# - 从 Excel 中读取(范围到多维数组)C#

python - 'utf- 8' codec can' t 解码字节 0xa3 在位置 28 : invalid start byte

python-2.7 - csv.DictReader 是否将文件存储在内存中?

javascript - 用于构造查询的 JSON 数据的有效方法

python - 在 PyCharm 中显示运行和调试工具栏

python - FFMPEG Loudnorm 读取 JSON 数据

Excel创建多重条件排名

excel - 类似于 VLookup 的函数,但返回每个相关的值