簡體   English   中英

如何使此python(使用openpyxl)程序運行更快?

[英]How can I make this python(using openpyxl) program run faster?

這是我的代碼:

import openpyxl
import os

os.chdir('c:\\users\\Desktop')
wb= openpyxl.load_workbook(filename= 'excel.xlsx',data_only = True)
wb.create_sheet(index=0,title='Summary')
sumsheet= wb.get_sheet_by_name('Summary')
print('Creating Summary Sheet')
#loop through worksheets
print('Looping Worksheets')
for sheet in wb.worksheets:
    for row in  sheet.iter_rows():
        for cell in row:
                 #find headers of columns needed
                if cell.value=='LowLimit':
                     lowCol=cell.column
                if cell.value=='HighLimit':
                     highCol=cell.column
                if cell.value=='MeasValue':
                     measCol=cell.column

                 #name new columns    
                sheet['O1']='meas-low'
                sheet['P1']='high-meas'
                sheet['Q1']='Minimum'
                sheet['R1']='Margin'

                 #find how many rows of each sheet
                maxrow=sheet.max_row
                i=0

                #subtraction using max row
                for i in range(2,maxrow+1):
                      if  sheet[str(highCol)+str(i)].value=='---':
                          sheet['O'+str(i)]='='+str(measCol)+str(i)+'-'+str(lowCol)+str(i)
                          sheet['P'+str(i)]='=9999'
                          sheet['Q'+str(i)]='=MIN(O'+str(i)+':P'+str(i)+')'
                          sheet['R'+str(i)]='=IF(AND(Q'+str(i)+'<3,Q'+str(i)+'>-3),"Marginal","")'
                      elif sheet[str(lowCol)+str(i)].value=='---':
                          sheet['O'+str(i)]='=9999'
                          sheet['P'+str(i)]='='+str(highCol)+str(i)+'-'+str(measCol)+str(i)
                          sheet['Q'+str(i)]='=MIN(O'+str(i)+':P'+str(i)+')'
                          sheet['R'+str(i)]='=IF(AND(Q'+str(i)+'<3,Q'+str(i)+'>-3),"Marginal","")'
                      else:
                          sheet['O'+str(i)]='='+str(measCol)+str(i)+'-'+str(lowCol)+str(i)
                          sheet['P'+str(i)]='='+str(highCol)+str(i)+'-'+str(measCol)+str(i)
                          sheet['Q'+str(i)]='=MIN(O'+str(i)+':P'+str(i)+')'
                          sheet['R'+str(i)]='=IF(AND(Q'+str(i)+'<3,Q'+str(i)+'>-3),"Marginal","")'

                ++i


print('Saving new wb')
import os 
os.chdir('C:\\Users\\hpj683\\Desktop')
wb.save('example.xlsx')

這運行得非常好,只是需要4分鍾才能完成一本excel工作簿。 有什么方法可以優化代碼以使其運行更快? 我的在線研究建議更改為read_only或write_only以使其運行更快,但是我的代碼需要讀寫excel工作簿,因此兩者均無效。

代碼可以從分解成單獨的功能中受益。 這將幫助您識別慢速位並逐步替換它們。

以下位不應該在每一行的循環中:

  • 查找標題
  • 調用ws.max_row這非常昂貴
  • ws["C" + str(i)] 使用ws.cell(row=i, column=3)

如果嵌套循環不是格式錯誤,那么為什么要嵌套呢?

另外,您還應該查看配置文件模塊,以找出速度較慢的模塊。 您可能想看一下我關於去年PyCon UK 上的openpyxl配置文件的演講

祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM