简体   繁体   中英

Saving Excel file from python script using win32com library

I am using win32com.client library to open xlsm file and save it to xls file. Yes I know some may raise the question that saving to old format should not be done but that is the requirement of the business - the recipients of files are mostly using old Excel versions so converting them into new one is not the option.

Going back to the problem. The code that is doing the conversion is the following:

excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(self.dicData["report_file_xlsm"])
excel.DisplayAlerts = False
wb.DoNotPromptForConvert = True
wb.CheckCompatibility = False
wb.SaveAs(r'output.xls', FileFormat=56, ConflictResolution=2)
excel.Application.Quit()

and it is working. However I would like to replace the output path to values generated by the script in the form of fixed output folder path plus generated name of output file. The path to output folder is kept in json that is read when the script starts and in json file it lookls like this:

C:\\DATA\\Program\\Output

that file is also generated in automatic way by command

os.getcwd()

The final version of save as command should looks like

wb.SaveAs(output_file, FileFormat=56, ConflictResolution=2)

where output_file is string variable created by concatenating output path with output file name generated by script. The problem is that this form of save as command generates exception:

(-2147352567, 'Exception occurred.', (0, 'Microsoft Excel',
"'C:\\//DATA/Program/Output/' cannot be accessed. The file may be
corrupted, located on a server that is not responding, or read-only.",
'xlmain11.chm', 0, -2146827284), None)

It is a bit strange to me as the opening command:

wb = excel.Workbooks.Open(self.dicData["report_file_xlsm"])

where the input file is provided also in form of dictionary entry of string type works without problems.

Problem solved using pathlib library.

the output_file variable is created using the following command

output_file = pathlib.Path('{}\{}.xls'.format(output_folder,output_file_name)

and then the variable output_file is used in following way

wb.SaveAs(str(output_file), FileFormat=56, ConflictResolution=2)

I don't know if that is the most proper solution but it works.

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