5

I am using python to open an excel file and make some changes and then I need to save it. I can get everything done except the save part. How do I get python to save the file. If I save it manual I get the pop up box and I can click save, but I don't want to have to manually click save. I want python to just save it and close excel. I need help, this is what I have. but it won't work. I can get it to save but not close????

 import win32com.client
 import os


 xl = win32com.client.DispatchEx("Excel.Application")
 xl.workbooks.open("C:\file.xlsm")
 xl.run("file.xlsm!macro")
 xl.Visible = True
 xl.save = true
 xl.close
Trying_hard
  • 8,931
  • 29
  • 62
  • 85

2 Answers2

8

You need to get a hook to the workbook object and apply the save as an argument to the close method:

xl = win32com.client.DispatchEx("Excel.Application")
wb = xl.workbooks.open("C:\file.xlsm")
xl.run("file.xlsm!macro")
xl.Visible = True
wb.Close(SaveChanges=1)
xl.Quit()
lu5er
  • 3,229
  • 2
  • 29
  • 50
0

Had the same issue, plus getting the values for formulas, this is what I did (this part is after I put the formulas in from a different place and saved the excel spreadsheet):

     import win32com.client as win

     xl=win.Dispatch('Excel.Application') 
     wb = xl.Workbooks.Open('filepath')
     xl.Visible = True
     wb.Close(SAVE_ATTRIBUTE_VALUES)
     xl.Quit()

then when you open the spreadsheet or call:

     wb = openpyxl.load_workbook('filepath', data_only=True)
     ws = wb.get_sheet_by_name('Sheet1')
     print ws['A1'].value

it gives you the value of whatever is loaded using the formula, but you might need to add some

    time.sleep(sek) 

to get it to wait for values to load before closing

kotbeg
  • 189
  • 1
  • 4