我能够打开已有的工作簿,但是我没有看到任何方法在该工作簿中打开预先存在的工作表。有没有办法做到这一点?
您无法使用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
但是,我发现读取数据并存储到二维数组更容易,因为我正在操作数据并一遍又一遍地接收输入,并且在测试结束之前不想写入excel文件(你可以轻松地使用xlsxwriter,因为这可能是他们所做的,直到你调用.close()
)。
在搜索了一些关于在xlxs中打开现有工作表的方法之后,我发现了
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')
您现在可以将任何数据附加/写入打开的工作表。我希望它有所帮助。谢谢