2013-08-01 96 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。 –

相关问题