Export data to Excel using macros via Open XML

I have an Excel worksheet that I use as a template file for exporting data.

An Excel worksheet is an XLSM file and contains several codes written in it in VBA.

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

I use the Open XML library for this.

The same thing works if I use the xlsx template file.

Is it not possible to write a macro in xlsm Excel via Open XML?

If so, any instructions that should be kept in mind.

+4
source share
1 answer

excel . Excel 2016 Workbook Macro Enabled Workbook, SaveMEW.xlsm , . , `_sourceFile.

    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();
            }
        }
+1

Source: https://habr.com/ru/post/1668912/


All Articles