我正在尝试将数据表流式传输到 MVC 中的 excel 文件。当行数超过 250,000 时,它会给我 OutOfMemory 异常。以下是代码:
var memStream = new MemoryStream();
var streamWriter = new StreamWriter(memStream);
streamWriter.WriteLine("{0}", "<TABLE>");
foreach (DataRow rw in dt.Rows)
{
streamWriter.WriteLine("{0}", "<TR>");
foreach (DataColumn cl in dt.Columns)
{
streamWriter.WriteLine("{0}", "<TD>");
streamWriter.WriteLine("{0}", rw[cl].ToString());
streamWriter.WriteLine("{0}", "</TD>");
}
streamWriter.WriteLine("{0}", "</TR>");
}
streamWriter.WriteLine("{0}", "</TABLE>");
streamWriter.Flush();
memStream.Seek(0, SeekOrigin.Begin);
return File(memStream, "application/vnd.ms-excel", "Test.xls");
我认为通过缓冲区写入内存流应该可以解决 OutOfMemory 问题。但是,我无法这样做。我应该如何修改上述代码以缓冲写入内存流?
谢谢