c# NOPI导出excel后 “发现有部分内容有问题 ”
查找网上的方法发现有以下几种:
1. workbook.Write(ms) 生成的 MemoryStream 后,使用了 ms.GetBuffer() 返回文件内容,导致生成的 Excel 文件结尾处有大量的 00(空字节),改为 ms.ToArray() 即可得到正常的文件了。
2.编码不一致。可以修改如下:
Response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet"; Response.AppendHeader("Content-Type", "text/html; charset=GB2312"); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", fileName)); Response.Charset = "GB2312"; Response.ContentEncoding = Encoding.GetEncoding("GB2312");
但是这两种都不是我的问题,最后发现,是流没有正常关闭。最后加了一句 Response.Close(); 问题解决。
具体代码示例如下:
/// /// 导出文件到浏览器 /// /// /// ///文件名称 private void ExportExcel(XSSFWorkbook workbook, HttpResponse Response, string fileName) { using (var exportData = new MemoryStream()) { workbook.Write(exportData); Response.Buffer = true; Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); //response.ContentType = "application/ms-excel"; Response.ContentType = "application/vnd.openxmlformats - officedocument.spreadsheetml.sheet"; Response.AppendHeader("Content-Type", "text/html; charset=GB2312"); // Response.AddHeader("Content-Length", exportData.Length.ToString()); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xlsx", fileName)); Response.Charset = "GB2312"; Response.ContentEncoding = Encoding.GetEncoding("GB2312"); Response.BinaryWrite(exportData.ToArray());// ms.ToArray() GetBuffer Response.Flush(); Response.Close(); } }