I'm using System.IO.Packaging to build simple Excel files. One of our customers would like to have an autorun macro that updates data and recalcs the sheet.
Pulling apart existing sheets I can see that all you need to do is add the vbaProject.bin file and change a few types in the _rels. So I made the macro in one file, extracted the vbaProject.bin, copied it into another file, and presto, there's the macro.
I know how to add package parts when they are in XML format, like the sheets or the workbook itself, but I've never added a binary file and I can't figure it out. Has anyone done this before?
Ok I got it. Following TnTinMn's suggestion:
Open a new workbook and type in your macro. Change the extension to zip, open it, open the
xlfolder and copy out thevbaProject.binto somewhere easy to find.In your .Net code, make a new Part and add it to the Package as 'xl/vbaProject.bin'. Copy over byte-for-byte from the
vbaProject.binyou extracted above. It will be compressed as you add the bytes.Then you have to add a relationship to the workbook that points to your new file. You can find those relationships in
xl/_rels/workbook.xml.rels.You also have to add a content type entry at the root of the document, which goes into the
[Content Types].xls. This happens automatically when you use the ContentType parameter of CreatePartAnd finally, change the extension to .xlsm or .xltm
I'm extracting the following from many places in my code, so this is pseudo...