【问题标题】:Python : Reading Large Excel Worksheets using OpenpyxlPython:使用 Openpyxl 读取大型 Excel 工作表
【发布时间】: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()

标签: python excel csv


【解决方案1】:

尝试使用 load_workbook() 类的 read_only=True 属性,这会导致您获得的工作表为 IterableWorksheet ,这意味着您只能迭代它们:您不能直接使用列/行号来访问其中的单元格值.这将根据documentation 提供near constant memory consumption

另外,您不需要关闭filewith 语句将为您处理。

例子-

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-

有时,您需要打开或编写非常大的 XLSX 文件,而 openpyxl 中的常用例程将无法处理该负载。幸运的是,有两种模式可以让您在内存消耗(几乎)恒定的情况下读取和写入无限量的数据。

【讨论】:

  • 如果我也需要写入文件怎么办?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2017-08-03
  • 2014-02-15
  • 2019-01-29
  • 2011-06-07
  • 2018-08-04
  • 2018-03-31
相关资源
最近更新 更多