我使用Open XML從MVC生成Excel文檔。使用OpenXML從MVC控制器只讀工作簿
的代碼如下:
public ActionResult ExcelReport()
{
var custId = 1234; //ToDo get from session when it is set
using (MemoryStream mem = new MemoryStream())
{
ExcelReportGenerator excel = new ExcelReportGenerator();
excel.CreateExcelDoc(mem);
var reportName = string.Format("MyReport_{0}.xlsx", custId);
return File(mem.ToArray(), System.Net.Mime.MediaTypeNames.Application.Octet, reportName);
}
}
我CreateExcelDoc方法如下:
public void CreateExcelDoc(MemoryStream mem)
{
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(mem, SpreadsheetDocumentType.Workbook);
//SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(mem, false);
//Code removed for brevity
worksheetPart.Worksheet.Save();
spreadsheetDocument.Close();
}
隨着創建方法如預期的Excel工作表被下載。不過,我想使工作簿只讀的,因此試圖在。開方法傳遞MEM流和isEditable設置爲false,但我得到一個YSOD時,我打了控制器錯誤Exception Details: System.IO.FileFormatException: Archive file cannot be size 0.
這正是我所需要的 - 謝謝:) –