I am trying to open an existing Excel 2013 file, add data and then save it(same name) and then close it and then close Excel. The code will open the file, select the correct worksheet and write the data, but when I try save it I get an attribute error. Am I missing a library or something? Here is the code:
我试图打开现有的Excel 2013文件,添加数据,然后保存(同名),然后关闭它,然后关闭Excel。代码将打开文件,选择正确的工作表并写入数据,但是当我尝试保存它时,我得到属性错误。我错过了图书馆吗?这是代码:
import win32com.client as win32
def Inventory_Status():
excel = win32.gencache.EnsureDispatch('Excel.Application') # opens Excel
wb = excel.Workbooks.Open(r'C:/pytest/Test.xlsx') # opens "Test" file
wb.Sheets(2).Select() # select 2nd worksheet "Aisle_2"
excel.Visible = True
excel.Range("A1").Select()
excel.ActiveCell.Value = "1234" # Fill in test data #
wb.save()
wb.Close()
excel.Quit()
Inventory_Status()
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr))
AttributeError: '<win32com.gen_py.Microsoft Excel 15.0 Object Library._Workbook instance at 0x5901424>' object has no attribute 'save'
2 个解决方案
#1
3
Capitalize the 's' on the save() method.
在save()方法上大写's'。
#2
2
According to this resource, you need to call SaveAs(xlsx_filepath)
on the workbook:
根据此资源,您需要在工作簿上调用SaveAs(xlsx_filepath):
def Inventory_Status():
excel = win32.gencache.EnsureDispatch('Excel.Application') # opens Excel
file_path = r'C:/pytest/Test.xlsx'
wb = excel.Workbooks.Open(file_path) # opens "Test" file
wb.Sheets(2).Select() # select 2nd worksheet "Aisle_2"
excel.Visible = True
excel.Range("A1").Select()
excel.ActiveCell.Value = "1234" # Fill in test data #
wb.SaveAs(file_path)
wb.Close()
excel.Quit()
#1
3
Capitalize the 's' on the save() method.
在save()方法上大写's'。
#2
2
According to this resource, you need to call SaveAs(xlsx_filepath)
on the workbook:
根据此资源,您需要在工作簿上调用SaveAs(xlsx_filepath):
def Inventory_Status():
excel = win32.gencache.EnsureDispatch('Excel.Application') # opens Excel
file_path = r'C:/pytest/Test.xlsx'
wb = excel.Workbooks.Open(file_path) # opens "Test" file
wb.Sheets(2).Select() # select 2nd worksheet "Aisle_2"
excel.Visible = True
excel.Range("A1").Select()
excel.ActiveCell.Value = "1234" # Fill in test data #
wb.SaveAs(file_path)
wb.Close()
excel.Quit()