簡體   English   中英

OpenXML PowerTools:是否可以將 Excel 電子表格寫入 a.Net MemoryStream?

[英]OpenXML PowerTools: is it possible to write an Excel spreadsheet to a .Net MemoryStream?

我正在使用 PowerTools 以編程方式創建 Excel 電子表格。

我使用 Nuget 在我的 C#/ASP.Net Core 項目中安裝了 PowerTools 4.5.3.2。 該項目還使用 DocumentFormat.OpenXml v2.9.1。

我可以生成電子表格了。

但...

我想將完成的電子表格作為 .Net MemoryStream 傳回給用戶。

我仔細研究了https://github.com/OfficeDev/Open-Xml-PowerTools上的 PowerTools 文檔和示例程序。

但在我的一生中,我還沒有看到任何方法讓 PowerTools 將生成的數據作為 MemoryStream 提供給我。 或者,就此而言,讓 PowerTools 使用我傳遞給它的 MemoryStream 的任何方式。

問:有什么建議嗎?

筆記

我想做的就是:

  1. 我的 ASP.Net web controller 調用 function 從頭開始生成一個 .xlsx 電子表格。

  2. function 使用 OpenXML PowerTools(因為這似乎是在.xlsx 中包含 Pivot 表的最直接方法)

  3. Once the function returns, the controller needs to return the.xlsx back to the web client as an Asp.Net Core FileStreamResult object.

換句話說,我想做的就是 go 從 2(工作)到 3(這就是我卡住的地方)。 我似乎無法將成功創建的電子表格“轉換”為與 MVC FileStreamResult 兼容的 object,以便 controller 傳回給調用者。

幫助!

不,OpenXml PowerTools 似乎不會讓您寫入除實際磁盤文件之外的任何內容。

所以我使用了一個臨時文件,然后將其轉換為 byte[] 數組以傳回給調用者:

using (OpenXmlMemoryStreamDocument streamDoc = OpenXmlMemoryStreamDocument.CreateSpreadsheetDocument())
{
    doc = streamDoc.GetSpreadsheetDocument();
    ms = new MemorySpreadsheet();
    ...
    string tmpFile = System.IO.Path.GetTempFileName();
    streamDoc.GetModifiedSmlDocument().SaveAs(tmpFile);
    byte[] fileBytes = System.IO.File.ReadAllBytes(tmpFile);
    return fileBytes;

PS:我從來沒有解決過這個問題: OpenXML SpreadsheetDocument SaveAs()giving file-in-use error

我最終放棄了 PowerTools,轉而使用全 OpenXml 解決方案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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