簡體   English   中英

如何在不創建本地文件的情況下使用 OpenXML 創建 Excel 文件?

[英]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並將其傳遞給MemoryStreamSpreadsheetDocument.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM