【发布时间】:2013-08-02 20:28:06
【问题描述】:
我能够打开我预先存在的工作簿,但我看不到任何方法可以打开该工作簿中的预先存在的工作表。有没有办法做到这一点?
【问题讨论】:
-
xlsxwriter 库用于编写 excel 文件 - 它无法读取它们。
标签: python worksheet xlsxwriter
我能够打开我预先存在的工作簿,但我看不到任何方法可以打开该工作簿中的预先存在的工作表。有没有办法做到这一点?
【问题讨论】:
标签: python worksheet xlsxwriter
您不能使用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')
您现在可以将任何数据附加/写入打开的工作表。 我希望它有所帮助。 谢谢
【讨论】:
您可以使用 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 的问题。”
【讨论】: