我想覆盖已经存在的 excel 文件中的特定单元格。我已经搜索并找到了这个答案,使用 xlwt 写入现有工作簿。我已将其应用如下,
def wrtite_to_excel (self):
#first I must open the specified excel file, sice open_file is in the same class, hence we can get it using self.sheet.
bookwt = copy(self.workbook)
sheetwt= bookwt.get_sheet(0)
#now, I must know the column that was estimated so I overwrite it,
colindex= self.columnBox.current() #returns the index of the estimated column
for i in range (1, self.grid.shape[0]):
if (str (self.sheet.cell_value(i,colindex)).lower () == self.missingBox.get().lower()):
#write the estimated value:
sheetwt.write (i, colindex, self.grid[i])
bookwt.save(self.filename + '.out' + os.path.splitext(self.filename)[-1])
请注意, self.workbook 已经以这种方式存在于同一类的另一个方法中,
def open_file (self, file_name):
try:
self.workbook = xlrd.open_workbook(file_name)
我真的不知道这是什么意思,'.out' + os.path.splitext(self.filename)[-1],但它似乎导致修改后的文件保存在与原始文件相同的路径中用不同的名字。
运行程序后,一个新的 Excel 文件将保存在与原始文件相同的路径中,但是它以一个奇怪的名称保存,data.xlsx.out.xlsx
并且无法打开。我认为这是由这条线引起的'.out' + os.path.splitext(self.filename)[-1]
。我删除了该行以覆盖原始文件而不保存副本,但是在运行程序时,我无法打开原始文件,并且收到一条错误消息,指出由于文件格式或文件无法打开文件扩展无效。
我真正想要的是修改原始文件而不是创建修改后的副本。
编辑:如果仅像这样指定文件名,SiHa 的答案可以修改现有文件而不创建副本,
bookwt.save(self.filename)
而且,它可以通过这种方式保存一个新副本,
filepath, fileext = os.path.splitext(self.filename)
bookwt.save(filepath + '_out' + fileext)
或者作为问题中我的代码中提供的行。但是,在所有这些方法中都存在相同的问题,修改文件后无法打开。经过搜索,我发现可以通过将原始文件的扩展名从.xlsx更改为.xls来解决问题。进行此更改后,问题得到解决。这是我找到解决方案的链接http://www.computing.net/answers/office/the-file-formatfile-extension-is-not-valid/19454.html
谢谢你。