首页 文章

使用POI读/写XLSM

提问于
浏览
1

我在我的c#代码中使用POI几周,我发现并发现我无法解决:Xlsm .

我要打开一个xlsm模板,编辑并保存 . 该模板包含宏,但我只是将数据添加到xlsm文件中 . 实际上,我认为Read和Edit正在工作中找到(感谢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();

例如,即使这个崩溃..

有人有想法吗?谢谢 !

1 回答

  • 0

    您需要以适当的格式编写宏嵌入文件,例如我读取.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类型here

相关问题