我可以打开已有的工作簿,但是我没有看到任何打开该工作簿内部现有工作表的方法。是否有任何方法可以做到这一点?
我可以打开已有的工作簿,但是我没有看到任何打开该工作簿内部现有工作表的方法。是否有任何方法可以做到这一点?
使用 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()
方法为止)。
xlrd==1.2.0
-- 这个版本可以读取 .xlsx 扩展名的文件。最新版的 xlrd 报错了。 - Mohamed Jaleel Nazirimport xlrd2 as xlrd
这样剩下的代码就能正常运行了。 - that_roy在搜索了一些关于在xlxs中打开现有表格的方法后,我发现
existingWorksheet = wb.get_worksheet_by_name('Your Worksheet name goes here...')
existingWorksheet.write_row(0,0,'xyz')