2013-08-01 97 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的唯一途徑是閱讀Excel文件xlrd然後通過行和列運行...

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

我真的止跌不說「極其複雜的結構」。該結構僅僅是一個表單的zipfile存檔,其中每個表單都是包含單元格內容的XML文件。 訪問,讀取和編輯相當簡單,只是XlsxWriter打算成爲**作家**。不是**讀者**。 –

+1

@AlexanderHuszagh謝謝! – dylnmc

+0

真棒,編輯後現在是一個很好的答案。 +1。 –

相關問題