写入损坏的 XLSX 文件 Response.OutputStream

Getting a corrupted XLSX file when writing it to Response.OutputStream

在 ASP.Net 中,我正在使用 NPOI 将保存写入 Excel 文档,并且我刚刚转到版本 2+。它可以很好地写入 xls,但切换到 xlsx 更具挑战性。我的新改进代码在输出文件中添加了大量 NUL 字符。

结果是Excel抱怨有"a problem with some content",我要他们尝试恢复吗?

这是一张用我的十六进制编辑器创建的 xlsx 文件的图片: BadXlsxHexImage 那些 00 持续了好几页。我从字面上删除了编辑器中的那些,直到文件打开没有错误。

为什么这段代码会向这个文件中添加这么多 NUL?

using (var exportData = new MemoryStream())
{
     workbook.Write(exportData);
     byte[] buf = exportData.GetBuffer();

     string saveAsFileName = sFileName + ".xlsx";

     Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
     Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}; size={1}", saveAsFileName, buf.Length.ToString()));
     Response.Clear();
     Response.OutputStream.Write(buf, 0, buf.Length);
     exportData.Close();
     Response.BufferOutput = true;
     Response.Flush();
     Response.Close();
}

(我已经试过用BinaryWrite代替OutputStream.WriteResponse.End代替Response.Close,并设置Content-Length的长度缓冲区。此外,none 这是写入 xls 的问题。)

您得到一堆空字节的原因是因为您使用的是 GetBuffer on the MemoryStream. This will return the entire allocated internal buffer array, which will include unused bytes that are beyond the end of the data if the buffer is not completely full. If you want to get just the data in the buffer (which you definitely do), then you should use ToArray

话虽如此,您为什么要写信给 MemoryStream?您已经有一个要写入的流:OutputStream。直接把工作簿写到那个就行了。

这样试试:

Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", saveAsFileName));
workbook.Write(Response.OutputStream);
Response.Flush();
Response.Close();