Python - excel:写入多个单元格需要时间 [英] Python - excel : writing to multiple cells takes time

查看:243
本文介绍了Python - excel:写入多个单元格需要时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用win32com.client将数据写入excel文件。
这需要太多时间(下面的代码模拟我想要更新excel的数据量,需要〜2秒)。

I'm using win32com.client to write data to an excel file. This takes too much time (the code below simulates the amount of data I want to update excel with, and it takes ~2 seconds).

是否有在一次呼叫中更新多个单元格(具有不同值)的方式,而不是一个接一个地填充它们?或者可能使用更有效的不同方法?

Is there a way to update multiple cells (with different values) in one call rather than filling them one by one? or maybe using a different method which is more efficient?

我使用的是python 2.7和office 2010。

I'm using python 2.7 and office 2010.

以下是代码:

from win32com.client import Dispatch

xlsApp   = Dispatch('Excel.Application')
xlsApp.Workbooks.Add()
xlsApp.Visible  = True
workSheet = xlsApp.Worksheets(1)

for i in range(300):
    for j in range(20):
        workSheet.Cells(i+1,j+1).Value = (i+10000)*j


推荐答案

一些建议:

屏幕更新,手动计算

尝试以下操作:

xlsApp.ScreenUpdating = False
xlsApp.Calculation = -4135 # manual
try:
    #
    worksheet = ...
    for i in range(...):
    # 
finally:
    xlsApp.ScreenUpdating = True
    xlsApp.Calculation = -4105 # automatic

一次分配多个单元格

使用VBA,可以将范围的值设置为数组。一次设置几个值可能会更快:

Using VBA, you can set a range's value to an array. Setting several values at once might be faster:

' VBA code
ActiveSheet.Range("A1:D1").Value = Array(1, 2, 3, 4)

我从未尝试过使用Python,我建议你尝试一下:

I have never tried this using Python, I suggest you try something like:

worksheet.Range("A1:D1").Value = [1, 2, 3, 4]

另一种方法

考虑使用 openpyxl xlwt 。 Openpyxls允许您创建 .xlsx 文件而不安装Excel。 Xlwt对 .xls 文件也是一样的。

Consider using openpyxl or xlwt. Openpyxls lets you create .xlsx files without having Excel installed. Xlwt does the same thing for .xls files.

这篇关于Python - excel:写入多个单元格需要时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆