我创建了一个 ASP.NET Mvc 自定义
FileResult
,它将导出工作簿 (.xlsx
)。
请参阅以下代码:
public class TestData
{
public string StudentName { get; set; }
public string Course { get; set; }
}
public class ExcelResult<T> : FileResult
{
private readonly List<TestData> _testDataList;
public ExcelResult(string fileName = "export.xlsx")
: base("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
FileDownloadName = fileName;
List<TestData> testDataList = new List<TestData>();
TestData td = new TestData();
TestData td1 = new TestData();
td.StudentName = "Student1";
td.Course = "BS IT";
td1.StudentName = "Student2";
td1.Course = "BS IT";
testDataList.Add(td);
testDataList.Add(td1);
_testDataList = testDataList;
}
protected override void WriteFile(HttpResponseBase response)
{
Stream output = response.OutputStream;
// create an Excel file objects
XSSFWorkbook workbook = new XSSFWorkbook();
// add a Sheet
ISheet sheet1 = workbook.CreateSheet("Sheet1");
// get list data
List<TestData> listRainInfo = _testDataList;
// to sheet1 add the title of the first head row
IRow row1 = sheet1.CreateRow(0);
row1.CreateCell(0).SetCellValue("Student Name");
row1.CreateCell(1).SetCellValue("Course");
// data is gradually written sheet1 each row
for (int i = 0; i < listRainInfo.Count; i++)
{
IRow rowtemp = sheet1.CreateRow(i + 1);
rowtemp.CreateCell(0).SetCellValue(listRainInfo[i].StudentName.ToString());
rowtemp.CreateCell(1).SetCellValue(listRainInfo[i].Course.ToString());
}
// Write to the client
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
output.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
在这行代码中抛出错误(无法访问关闭的流):
output.Write(ms.GetBuffer(), 0, (int)ms.Length);
我在这里遗漏了什么吗?
我刚刚弄清楚出了什么问题。由于某种原因,一旦 NPOI 在流中完成工作簿的编写,它就会将其关闭。
因此,为了使代码正常工作,我们需要这样做:
MemoryStream ms = new MemoryStream();
workbook.Write(ms);
var buffer = ms.ToArray();
var bytesRead = buffer.Length;
然后我们现在可以将其传递给客户端:
response.OutputStream.Write(buffer, 0, btyesRead);
这会在 google 中显示一些术语,因此这里是 ASP.NET Core 的版本;
var mem = new MemoryStream();
wb.Write(mem, true);
mem.Position = 0;
return File(mem, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"{key}_{Guid.NewGuid()}.xlsx");
这里的关键是
.Write(mem, true);
,其中 leaveOpen
设置为 true。 Controller.File
关闭内存流。