簡體   English   中英

使用 MemoryStream 創建 Open XML 電子表格時的 Excel 和“不可讀的內容”

[英]Excel and “unreadable content” when creating an Open XML spreadsheet with MemoryStream

When creating an Excel spreadsheet using the Open XML SDK v2.0, our Excel output initially worked successfully for a number of months. 最近Excel(所有版本)開始抱怨“Excel在'zot.xlsx'中發現不可讀的內容。你想恢復這個工作簿的內容嗎?”。 我們在 web 應用程序中創建文件,使用MemoryStream作為存儲,然后在 HTTP 響應中作為byte[]發送,MIME 類型為"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" 壞文件的解壓縮內容與文件的解壓縮內容相同,沒有錯誤。

我們追了太多小時,一路上撿了幾個紅鯡魚,但最后,解決了壞文件在一個方面是不同的。 文件長度不同。 在返回MemoryStream並將byte[]寫入 HTTP 響應之前,請確保使用簡單的stream.Capacity = (int)stream.Length;截斷MemoryStream以使其容量和長度相同。 .

似乎 Excel 現在將文件中的額外內容檢測為“不可讀內容”作為安全風險,並拋出令人討厭的錯誤,而過去它會接受風險。

注意:答案取自原始發布者,之前在他的問題中有答案

逐一檢查以下內容以消除 excel 中的“不可讀內容錯誤”。

1.確保正確的數據以正確的方式寫入正確的單元格。 對所有單元格執行此操作。可能會在一次單元格中錯誤寫入數據導致此問題。正確使用單元格索引。

2.嘗試使用 Cell.DataType = new EnumValue(CellValues.String) 而不是共享字符串。這可能有助於消除錯誤。

3.如果任何單元格包含#VALUE/#REF/#NAME? 或#DIV 錯誤,刪除那些錯誤。

4.從服務器下載文件時出現此問題。 在 web 應用程序中創建 excel 電子表格,使用 MemoryStream 並下載該電子表格。

使用以下代碼:HttpContext.Current.Response.Clear()

  Response.ClearHeaders()  

  Response.Buffer = False

  msReportStream = CType(controller.GetFromSession  
       (Constants.SESSION_REPORT), MemoryStream)

  Response.ContentType = "application/vnd.openxmlformats-  
       officedocument.spreadsheetml.sheet"

   Response.AddHeader("Connection", "Keep-Alive")

   Response.AddHeader("Content-Disposition", String.Format("attachment;  
       filename={0}", strReportFileName))

   Response.ContentEncoding = Encoding.UTF8

   Response.BinaryWrite(msPNLReportStream.ToArray())

   Response.Flush()

   Response.Close()

   Response.End()--use this when the code is deployed in server only not required in local.gives error in local.

   msReportStream.Dispose()

   msReportStream.Close()

如果您使用的是 ASPOSE 技術,請使用

Me.Response.Clear()

Me.Response.Buffer = False

Me.Response.AddHeader("Accept-Ranges", "bytes")

Response.ContentType = "application/octet-stream"

Response.AddHeader("Connection", "Keep-Alive")

Response.ContentEncoding = Encoding.UTF8

asposeReport.ShowSavePopUp(Me.Response, controller.GetFromSession(Constants.SESSION_REPORT), strReportFileName)
                                                                                                       Me.Response.Flush()
            Me.Response.Close()
            Me.Response.End()

使用 Open XML SDK 2.5 Productivity Tool for Microsoft Office 打開.xlsx 文件並驗證文檔,這將為您提供任何導致內容不可讀的驗證錯誤

暫無
暫無

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

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