【问题标题】:Speed up reading a large Excel worksheet using Python (openpyxl)使用 Python (openpyxl) 加快读取大型 Excel 工作表的速度
【发布时间】:2020-07-24 04:12:47
【问题描述】:

我正在尝试读取和清理 Excel 工作表中的数据,并将清理后的数据导入 MySQL 数据库。我的问题是 Excel 工作表的阅读部分花费了太长时间。我想尽可能优化这个时间。

我尝试了以下方法:

from openpyxl import load_workbook
from openpyxl.utils.dataframe import dataframe_to_rows


start_time = datetime.datetime.now()

wb = load_workbook(filename='Book1.xlsx', read_only=True, data_only=True)
ws=wb.active
column = ws.max_column
row = ws.max_row

for i in range(1, row+1):
    for j in range(1, column+1):
        cell_obj = ws.cell(row=i, column=j)
        if cell_obj.value != None:
            print(cell_obj.value)
    print('----------------This Row this execute--------------------------------')

end_time = datetime.datetime.now()
print(end_time-start_time)

我非常感谢任何建议,例如 Cython,但请不要建议使用 CSV 文件。

【问题讨论】:

  • 我在git 上有未解决的问题。寻求帮助。

标签: python python-3.x python-2.7 cython cythonize


【解决方案1】:

我强烈建议使用 Pandas,因为它具有 read_excelto_sql 函数,这正是您想要做的。此外,Pandas 的速度非常快。

语法和最佳实践意味着您的代码将如下所示:

df = pd.read_excel("path/to/file")
df.to_sql("a_connection_string")

真的,就是这样!

【讨论】:

  • 感谢您的回复,但由于一次读取所有行而导致 MemoryError。有什么方法可以读取分块数据,因为我想清理我的 excel 然后导入 SQL
  • 最终,Pandas read_excel 使用 openpyxlxlrd 之一,因此速度不太可能快得多
  • @DavidW 我完全同意你的看法。我可以通过将 excel 解压缩到 xml 来读取这个 excel,并尝试更快地读取这个 xml 表。 ThankyouGuysForyourSupports
猜你喜欢
  • 2015-09-20
  • 1970-01-01
  • 2020-04-09
  • 2017-08-03
  • 2019-01-29
  • 2014-02-15
  • 1970-01-01
  • 2018-04-24
  • 1970-01-01
相关资源
最近更新 更多