我想覆盖已经存在的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
谢谢。
要解释该行:
(self.filename + '.out'
意味着将“ .out”连接到原始文件名的末尾。
+ os.path.splitext(self.filename)[-1])
意味着将文件名分割为一个列表,['path', 'extension']
然后将最后一个元素(扩展名)重新连接到末尾。
所以你最终 data.xlsx.out.xlsx
您应该只能使用bookwt.save(self.filename)
,尽管如果您仍然可以打开文件进行读取,则可能会遇到错误。以与上述类似的方式创建副本可能更安全:
filepath, fileext = os.path.splitext(self.filename)
bookwt.save(filepath + '_out' + fileext)
哪个应该给你 data_out.xlsx
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句