我想覆蓋已存在的excel文件中的特定單元格。我已經搜索並找到了這個答案,writing to existing workbook using xlwt。我申請它下面,使用python寫入特定的Excel工作表
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
謝謝。
非常感謝SiHa,我添加了2行,但是我遇到了同樣的問題。複製的文件成功保存在路徑中,但無法打開我收到了與問題中提到的相同的錯誤消息。搜索後,我發現,如果原始文件以擴展名xls而不是xlsx保存,則可以解決此問題。我剛剛更改了文件擴展名,並且文件已成功修改,但未創建新副本。我也可以使用通過將xls連接到文件名所提供的相同行來創建副本。現在它的工作,非常感謝:) – Dania
啊,是的。 Xlwt似乎只支持.xls看到[this](http://stackoverflow.com/a/21635803/3714940)問題。您可能需要查看[openpyxl](https://openpyxl.readthedocs.org/en/latest/)以獲取.xlsx支持 – SiHa