1

我在我的 c# 代码中使用 POI 几个星期了,我发现并解决了我无法解决的问题:Xlsm。

我必须打开一个 xlsm 模板,对其进行编辑并保存。模板包含宏,但我只是将数据添加到 xlsm 文件中。实际上,我认为 Read 和 Edit 正在工作 find (感谢在 vs 中调试),问题是当我尝试编写时......代码正在工作,没有错误,但是当我尝试用 Excel 打开它时,它崩溃了..

FileStream temp = new FileStream(xlsm_file, FileMode.Open, FileAccess.ReadWrite);
XSSFWorkbook workbook = (XSSFWorkbook)WorkbookFactory.Create(temp);
XSSFSheet sheet = (XSSFSheet)workbook.GetSheetAt(0);
workbook.SetSheetName(0, sheetname.Substring(0, Math.Min(sheetname.Length, 30)));
temp.Close();
FileStream toWrite = new FileStream(xlsm_file, FileMode.Open, FileAccess.ReadWrite);
workbook.Write(toWrite);
toWrite.Close(); 

例如,即使这崩溃了..

有人有想法吗?谢谢 !

4

1 回答 1

1

您需要以适当的格式编写宏嵌入文件,例如我读取 .xltm 文件并使用其 MIME 类型写入 .xltm 。看下面的功能

     public ActionResult DownloadXLTMFile()
            {
                try
                {
                  //Get your macro enabled file after manipulation
                   MemoryStream excelMS =  .....
                   //Using Resposne Stream to Make File Available for User to Download;
                    Response.Clear();

                    Response.ContentType = "application/vnd.ms-excel.template.macroEnabled.12";
                    Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}",  "YourFileName.xltm"));

                    Response.BinaryWrite(excelMS.ToArray());
                    Response.End();
                }
                catch (Exception Ex)
                {  }
                finally
                {}
                return View();
            }

您可以在此处找到合适的 MIME 类型

于 2017-07-06T17:35:53.850 回答