Python - excel : writing to multiple cells takes time

后端 未结 3 1270
没有蜡笔的小新
没有蜡笔的小新 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:08

    used the range suggestion of the other answer, I wrote this:

    def writeLineToExcel(wsh,line):
        wsh.Range( "A1:"+chr(len(line)+96).upper()+"1").Value=line
    
    xlApp = Dispatch("Excel.Application")
    xlApp.Visible = 1
    xlDoc = xlApp.Workbooks.Open("test.xlsx")
    wsh = xlDoc.Sheets("Sheet1")
    writeLineToExcel(wsh,[1, 2, 3, 4])
    

    you may also write multiple lines at once:

    def writeLinesToExcel(wsh,lines): # assume that all lines have the same length
        wsh.Range( "A1:"+chr(len(lines)+96).upper()+str(len(lines[0]))).Value=lines
    
    writeLinesToExcel(wsh,[ [1, 2, 3, 4],
                            [5, 6, 7, 8],
                            [9, 10,11,12],
                            [13,14,15,16],
                            ])
    

提交回复
热议问题