Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export data to Excel Macro-enabled through Open XML

I have an Excel Sheet which I am using as a template file for exporting data.

The Excel Sheet is XLSM file and has few codes written in it in VBA.

Each time the file is copied and renamed with time stamp and data should be written to copied xlsm file but it is not writing the data.

I am using Open XML library for this.

The same is working if I use xlsx template file.

Is it not possible to write on xlsm Excel Macro-enabled through Open XML?

If yes, Any instructions to keep in mind.

like image 329
sunny Avatar asked Feb 06 '17 08:02

sunny


People also ask

Does XLTX allow macros?

There will not be any macros in an . XLTX. You can try renaming the file as . XLSM or .

Can you send macro-enabled workbook?

Paste your Personal. xlsb file into the Excel folder. If you have one or just a few macros that you want to share with others, you can send them the workbook that contains them. You can also make the workbook available on a shared network drive or from a SharePoint Services library.


1 Answers

The code in this answer will copy any excel file and switch it to a Macro Enabled Workbook. I have tested it against a simple Excel 2016 Workbook and Macro Enabled Workbook it creates a new file SaveMEW.xlsm in the same directory that the source file lives. Make sure the full path of the source file is put into `_sourceFile variable.

    var _sourceFile = " PATH TO YOUR TEMPLATE FILE ";

    using (var templateFile = File.Open(_sourceFile, FileMode.Open, FileAccess.Read))
        {
            using (var stream = new MemoryStream())
            {
                templateFile.CopyTo(stream);
                using (var spreadsheetDocument = SpreadsheetDocument.Open(stream, true))
                {                
                    spreadsheetDocument.ChangeDocumentType(SpreadsheetDocumentType.MacroEnabledWorkbook);
                }
                byte[] buffer = stream.ToArray();
                MemoryStream ms = new MemoryStream(buffer);
                FileStream file = new FileStream(System.IO.Path.GetDirectoryName(_sourceFile) + "/SaveMEW.xlsm",
                    FileMode.Create, FileAccess.Write);
                ms.WriteTo(file);
                file.Close();
            }
        }
like image 183
Taterhead Avatar answered Oct 22 '22 08:10

Taterhead