天天看點

為python-docx插入表格提速

為python-docx插入表格提速

用Python-docx在Word中插入表格時,速度慢到無法接受(插入500行9列的表格,大概耗時2~3分鐘),也是電腦的性能比較差,但無法保證使用者的電腦性能會高到哪兒去。

搜尋解決方案,多是使用Table._cells變量代替Table.add_row()函數,但這方案在我這兒竟然沒起什麼作用,不知道是哪兒的問題。貼一篇此方案的參考:“代碼一字狂” 寫的 python-docx 添加表格時很慢的解決方法

後來嘗試減少插入資料的行數,發現每次調用add_table()函數插入3行表格時,插入500行的總體耗時最短(6秒左右),這雖然與常識(重複的操作在批量執行時性能最好)相悖,但确實解決了問題。看來python-docx内部有些特殊的處理。

不算正式的python程式員,沒有繼續深入探索,請大家見諒哈!

相關代碼如下,比較簡單,沒加注釋:

RowPerTimes = 3    
    rowIndex = 0
    isOver = False
    while True:
        remainder = totalCount - rowIndex
        if remainder > RowPerTimes:
            remainder = RowPerTimes
        else:
            isOver = True

        table = doc.add_table(rows=remainder, cols=columnCount, style="Table Grid")
        for i in range(remainder):
            rowCells = table.row_cells(i)
            colIndex = 0
            for c in data[rowIndex]:
                rowCells[colIndex].text = c
                colIndex += 1
            rowIndex += 1
        
        if isOver:
            break
           

繼續閱讀