2013-08-01 23 views
10

既存のワークブックを開くことはできますが、そのワークブック内に既存のワークシートを開く方法はありません。これを行う方法はありますか?xlsxwriter:ブックに既存のワークシートを開く方法はありますか?

+2

[xlsxwriter](https://pypi.python.org/pypi/XlsxWriter)ライブラリは、Excelファイルを書き込むためのライブラリです。読み込めません。 – alecxe

+1

この http://stackoverflow.com/questions/18849535/how-to-write-update-data-into-cells-of-existing-xlsx-workbook-using-xlsxwriter-i – shellbye

答えて

15

xlsxwriterで既存のxlsxファイルに追加することはできません。

openpyxlというモジュールがあり、既存のExcelファイルを読み書きできるようになっていますが、その方法にはExcelファイルからの読み込み、すべての情報の保存(データベースまたは配列)、 workbook.close()に電話すると書き換えられ、すべての情報がxlsxファイルに書き込まれます。

同様に、独自の方法を使用してxlsxドキュメントに「追加」することができます。私は最近、xlsxファイルに追加する必要がありました。なぜなら、GPSデータをメインのワークシートに入れて、さまざまなテストをしてから、テストが始まるたびに新しいシートを追加しなければならなかったからです。私はopenpyxlせずにこの問題を回避することができる唯一の方法は... xlrdでExcelファイルを読み込んで、行と列を介して実行することでした

すなわち

cells = [] 
for row in range(sheet.nrows): 
    cells.append([]) 
    for col in range(sheet.ncols): 
     cells[row].append(workbook.cell(row, col).value) 

あなたはしかし、配列を必要としません。たとえば、これは完全に正常に動作します:

import xlrd 
import xlsxwriter 

from os.path import expanduser 
home = expanduser("~") 

# this writes test data to an excel file 
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home)) 
sheet1 = wb.add_worksheet() 
for row in range(10): 
    for col in range(20): 
     sheet1.write(row, col, "test ({}, {})".format(row, col)) 
wb.close() 

# open the file for reading 
wbRD = xlrd.open_workbook("{}/Desktop/test.xlsx".format(home)) 
sheets = wbRD.sheets() 

# open the same file for writing (just don't write yet) 
wb = xlsxwriter.Workbook("{}/Desktop/test.xlsx".format(home)) 

# run through the sheets and store sheets in workbook 
# this still doesn't write to the file yet 
for sheet in sheets: # write data from old file 
    newSheet = wb.add_worksheet(sheet.name) 
    for row in range(sheet.nrows): 
     for col in range(sheet.ncols): 
      newSheet.write(row, col, sheet.cell(row, col).value) 

for row in range(10, 20): # write NEW data 
    for col in range(20): 
     newSheet.write(row, col, "test ({}, {})".format(row, col)) 
wb.close() # THIS writes 

はしかし、私は、データを操作したと何度も何度も入力を受けていたので、データを読み取り、2次元配列に格納するために簡単だったことが判明し、テストが終わるまでExcelファイルに書きたいとは思っていませんでした.xlsxwriterと同じように簡単にできるのは、.close()に電話するまではおそらく何とかしているからです。

+0

を参照してください、私は本当にwouldn 「非常に複雑な構造」とは言いません。この構造は、各シートがセルの内容を含むXMLファイルであるシートのzipfileアーカイブです。 XlsxWriterは、** writer **の意向で、アクセス、閲覧、編集が非常に簡単です。 **読者**ではありません。 –

+1

@AlexanderHuszaghありがとう! – dylnmc

+0

驚くばかりです、編集後の優れた答えです。 +1。 –

関連する問題