close
這幾日遇到的C#使用 NPOI進行匯出時的問題
1. 匯出Excel的xlsx檔後,打開時MicroOffice系列打開時會提示 : 我們發現 "XXXX.xlsx"的部分內容有問題,您要我門盡可能嘗試復原嗎? 如果您信任此活頁簿的來源,請案一下[是]。
解決方案-
測試環境 : Office Excel 2007 2013 2019
FileStream fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/Resources/Template/" + strHeaderText + ".xlsx"), FileMode.Create, FileAccess.Write); workbook.Write(fileStream); //调用这个后会关于文件流,在HSSFWorkbook不会关闭所以在处理时应注意 FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("~/Resources/Template/" + strHeaderText + ".xlsx"), FileMode.Open, FileAccess.Read); long fileSize = fs.Length; //加上設置大小來下載xlsx,開啟時才不會報錯 HttpContext.Current.Response.AddHeader("Content-Length", fileSize.ToString()); byte[]fileBuffer = new byte[fileSize]; fs.Read(fileBuffer, 0, (int)fileSize); HttpContext.Current.Response.BinaryWrite(fileBuffer); fs.Close();
推測原因:
後端C#使用字串流給brower下載,收到資訊後重組檔案時沒加入定義的大小,導致Offoce認證失敗
來源文檔:
2.XSSFWorkbook對比寫方法Sending MemoryStream對比,參與關聯的次數。導Return Response.OutputStream會議?
HSSFWorkbook對象則不會,針對這個問題還專門查了一下HSSFWorkbook源代碼下有,基本是XSXSWorkbook的源代碼,目前已減少。
解決方案-
FileStream fileStream = new FileStream(HttpContext.Current.Server.MapPath("~/Resources/Template/" + strHeaderText + ".xlsx"), FileMode.Create, FileAccess.Write); workbook.Write(fileStream); //调用这个后会关于文件流,在HSSFWorkbook不会关闭所以在处理时应注意 FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("~/Resources/Template/" + strHeaderText + ".xlsx"), FileMode.Open, FileAccess.Read); long fileSize = fs.Length; byte[]fileBuffer = new byte[fileSize]; fs.Read(fileBuffer, 0, (int)fileSize); HttpContext.Current.Response.BinaryWrite(fileBuffer); fs.Close();
3.今天處理Excel2007、2010文件,格式.xlsx文件存在一個問題,在調用 Write方法之後關閉了傳入的文件流。
解決方案-
public override void Write(Stream stream) { byte[]bytes = GetBytes(); POIFSFileSystem fs = new POIFSFileSystem(); // For tracking what we've written out, used if we're // going to be preserving nodes List < string > excepts = new List < string > (1); MemoryStream newMemoryStream = new MemoryStream(bytes); // Write out the Workbook stream fs.CreateDocument(newMemoryStream, "Workbook"); // Write out our HPFS properties, if we have them WriteProperties(fs, excepts); if (preserveNodes) { // Don't Write out the old Workbook, we'll be doing our new one excepts.Add("Workbook"); // If the file had WORKBOOK instead of Workbook, we'll Write it // out correctly shortly, so don't include the old one excepts.Add("WORKBOOK"); // Copy over all the other nodes to our new poifs CopyNodes(this.filesystem, fs, excepts); } fs.WriteFileSystem(stream); fs.Dispose(); newMemoryStream.Dispose(); bytes = null; }
文章標籤
全站熱搜
留言列表