我想覆盖现有excel文件中的特定单元格。我搜索并找到了这个答案,writing to existing workbook using 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.工作簿已经存在于同一个类中的另一个方法中
^{pr2}$
我真的不知道这是什么意思,'.out'+os.path.splitext操作系统(self.filename文件名)[-1],但它似乎会导致修改后的文件以不同的名称保存在原始文件的同一路径中。在
运行程序后,一个新的Excel文件保存在原始文件的相同路径中,但是它以一个奇怪的名称保存为data.xlsx.out.xlsx,并且它不会打开。我想是这条线引起的。我删除了那一行是为了覆盖原始文件,不保存副本,但是当运行程序时,我无法打开原始文件,并且我收到一条错误消息,说文件无法打开,因为文件格式或扩展名无效。在
我真正想要的是修改原始文件而不是创建修改后的副本。在
编辑:如果文件名是这样指定的,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
谢谢。在