2016-12-21 5 views
0

私は年の各月のデータを含む別々のスプレッドシートを持っています - 合計12スプレッドシート。各ワークブックには200k〜500k行が含まれています。openpyxlスプレッドシートを整理する

1月

| name | course | grade | 
|-------|---------|-------| 
| dave | math | 90 | 
| chris | math | 80 | 
| dave | english | 75 | 

2月

| name | course | grade | 
|-------|---------|-------| 
| dave | science | 72 | 
| chris | art  | 58 | 
| dave | music | 62 | 

私は、毎月のブックを開く各行を反復処理し、各セルや個人ブックに関連するデータを書き込むことopenpyxlを使用しています。つまり、Chrisに属するすべての行は「Chris.xlsx」になり、Daveに属する行は「Dave.xlsx」に移動します。

私が遭遇している問題は、openpyxlがであり、極端にが遅いということです。私はそれが私のコードが非常に手続き的であり、反復と文章を最適化していないためだと確信しています。

ご意見は大変ありがとうございます。

def appendToWorkbooks(): 
    print("Appending workbooks") 
    je_dump_path = "C:/test/" 

    # define list of files in path 
    je_dump_files = os.listdir(je_dump_path) 

    # define path for resultant files 
    results_path = "C:/test/output/" 

    max_row = 0 
    input_row = 1 

    for file in je_dump_files: 
     current_row = 1 

     # load each workbook in the directory 
     load_file = je_dump_path + file 
     print("Loading workbook: " + file) 
     wb = load_workbook(filename=load_file, read_only=True) 
     print("Loaded workbook: " + file) 

     # select the worksheet with the name Sheet in each workbook 
     ws = wb['Sheet'] 
     print("Loaded worksheet") 

     # iterate through the rows in the currently open workbook 
     for row in ws.iter_rows(): 

      # determine the person this row of data relates to 
      person = ws.cell(row=current_row, column=1).value 

      # set output workbook to that person 
      output_wb_file = results_path + person + ".xlsx" 
      output_wb = load_workbook(output_wb_file) 
      output_ws = output_wb["Sheet"] 

      # increment the current row 
      current_row = current_row + 1 

      print("Currently on row: " + str(current_row)) 

      # determine the last row in the current output workbook 
      max_row = output_ws.max_row 

      # set the output row to the row after the last row in the current output workbook 
      output_row = max_row + 1 

      for cell in row: 
       output_ws.cell(row=output_row, column=column_index_from_string(cell.column)).value = cell.value 
      output_wb.save(output_wb_file) 
+0

あなたはhttp://stackoverflow.com/questions/35823835/reading-excel-file-is-magnitudes-slower-using-openpyxl-compared-to-に同様のポストを支援していたマイク・ミュラーソー@ xlrd – stutch

答えて

0

この行は、ループ内に持っていることは非常に高価である: max_row = output_ws.max_row

しかし、あなたは本当にあなたのファイルとあなたが見ているパフォーマンスに関するより詳細な情報を提供する必要があります。個々のファイルの大きさはどれくらいですか?個別にロードするのにどれくらい時間がかかりますか?など

+0

返事をありがとう。個々のファイルの範囲は41MB〜150MB(c。200k〜900k)です。 82行を通過するには約30秒かかります。 12個のワークブックに200k行があると仮定すると、これは完了するまでに約10日間かかります。 – stutch

+0

'ws.iter_rows'ループ内で' ws.cell'を呼び出さないでください。特に、読み込み専用モードでは行いません。これにより、openpyxlはファイルの解析を再開します。各行のセルをループするだけで済みます。あなた自身が行を増やさず、列挙を使ってカウンタを取得してください。ドキュメントをお読みください。 –

+0

チャーリーに感謝します。私はドキュメントを読もうとしました。 write_onlyモードを使用して、新しいスプレッドシートに行全体を書き込むほうが速いのではないでしょうか?私はこれを達成する方法がわかりませんが。あなたの助けに感謝します。 – stutch

関連する問題