5

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:

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'
4
  • I'm confused, why do you have the raise line in your post? Is that in your script? Did that get printed when you ran your script? Commented Jul 28, 2015 at 15:47
  • 4
    Don't use the module, but just looking at the continuity of your code: should the 's' on save be capitalized?
    – Alecg_O
    Commented Jul 28, 2015 at 15:50
  • @SuperBiasedMan that's probably just the traceback Commented Jul 28, 2015 at 15:53
  • @TankorSmash Oh, right now I see. The module is manually raising the error, and it's referencing that line as where the error originates from. Thanks, that was confusing me for a second there. Commented Jul 28, 2015 at 15:56

2 Answers 2

5

Capitalize the 's' on the save() method.

2
  • Thank you Alecg_O! That was it. I don't mean to use harsh language, but i'm an idiot. I looked at a lot of documentation and tried a lot of different things, and in the end it was something simple. I will be more diligent in the future. Thank you again.
    – JeffC
    Commented Jul 28, 2015 at 16:25
  • You're fine, it happens to the best of us - sometimes all it takes is a new set of eyes.
    – Alecg_O
    Commented Jul 28, 2015 at 17:37
2

According to this resource, you need to call SaveAs(xlsx_filepath) on the workbook:

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()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.