我在我的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();
例如,即便这样崩溃..
有人有想法吗? 谢谢!
答案 0 :(得分: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类型here