Python - excel : writing to multiple cells takes time

后端 未结 3 1269
没有蜡笔的小新
没有蜡笔的小新 2021-02-10 14:40

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 sec

3条回答
  •  逝去的感伤
    2021-02-10 15:11

    A few suggestions:

    ScreenUpdating off, manual calculation

    Try the following:

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

    Assign several cells at once

    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)
    

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

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

    A different approach

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

提交回复
热议问题