简体   繁体   中英

python Win32 Save

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM