简体   繁体   中英

Losing macros when adding data to excel spread sheet in python

I am trying to generate reports for a web project. The reports require I fill an excel spreadsheet with data and then run a macro to generate the details.

Using the following code

   from xlrd import open_workbook
   from xlutils.copy import copy
   import StringIO

   contents=open_workbook("filename.xls")
   cloneContents = copy(contents)

   #code for adding data to cloneContents here
   stream = StringIO()
   cloneContents.save(stream)

   #this is from a web app so this is stream sent to the user to download
   return stream

This all works fine except the cloned file appears to lose all the macros. I had a look around for other solutions, but the only one I could see involved actually loading the file in excel which I can't do because this is a linux server. Does anyone have any ideas what could be done? Thanks

This cannot be done with xlrd and xlutils.

But it can be done using this branch https://bitbucket.org/amorris/openpyxl/overview of openpyxl.

The key line is contents = load_workbook('filename.xlsm', keep_vba = True);

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