我能够打开我预先存在的工作簿,但我看不到任何方法可以在该工作簿中打开预先存在的工作表。有没有办法做到这一点?
3 回答
您不能附加到现有的 xlsx 文件xlsxwriter
。
有一个名为openpyxl的模块允许您读取和写入预先存在的 excel 文件,但我确信这样做的方法包括从 excel 文件中读取,以某种方式存储所有信息(数据库或数组),然后在何时重写您调用workbook.close()
它会将所有信息写入您的 xlsx 文件。
同样,您可以使用自己的方法“附加”到 xlsx 文档。我最近不得不附加到一个 xlsx 文件,因为我有很多不同的测试,其中我有 GPS 数据进入主工作表,然后每次测试开始时我都必须附加一个新工作表。没有openpyxl我可以解决这个问题的唯一方法是用xlrd读取excel文件,然后遍历行和列......
IE
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')
您现在可以将任何数据附加/写入打开的工作表。我希望它有所帮助。谢谢
您可以使用workbook.get_worksheet_by_name()功能: https ://xlsxwriter.readthedocs.io/workbook.html#get_worksheet_by_name
根据https://xlsxwriter.readthedocs.io/changes.html,该功能已于 2016 年 5 月 13 日添加。
“发布 0.8.7 - 2016 年 5 月 13 日
- 修复在 Windows 上插入只读图像时的问题。问题 #352。
-添加了 get_worksheet_by_name() 方法以允许通过其名称从工作簿中检索工作表。
- 修复了内部文件创建和修改日期在本地时区而不是 UTC 的问题。”