[英]How to create Excel file using OpenXML without creating a local file?
是否可以在不創建本地文件的情況下使用 OpenXML SDK 創建和編輯 Excel 文檔?
根據文檔, Create
方法需要一個filepath
,它創建文件的本地副本。
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);
我在這里指的是 MSDN 文章: https : //msdn.microsoft.com/en-us/library/office/ff478153.aspx
我的要求是創建文件,並且應該通過單擊按鈕由瀏覽器下載。
有什么建議嗎?
您可以使用采用Stream
並將其傳遞給MemoryStream
的SpreadsheetDocument.Create
的重載:
MemoryStream memoryStream = new MemoryStream();
SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(memoryStream, SpreadsheetDocumentType.Workbook);
//add the excel contents...
//reset the position to the start of the stream
memoryStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(memoryStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
請注意,根據此 StackOverflow 問題,您不需要處置 Stream,因為FileStreamResult
類將為您完成。
添加另一個答案,因為我花了太多時間搜索這個:另一種將 SpreadsheetDocument 保存到流的方法是調用SpreadsheetDocument.Clone(Stream s)
它的好處是即使您從文件或不想保存的流創建文檔,也可以保存到流。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.