简体   繁体   English

使用自定义 FileResult 在 NPOI 库中创建输出工作簿

[英]Outputing workbook create in NPOI library using custom FileResult

I created an ASP.NET Mvc custom FileResult that will export a workbook( .xlsx ).我创建了一个 ASP.NET Mvc 自定义FileResult ,它将导出一个工作簿( .xlsx )。

See the codes below:请参阅以下代码:

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);
    }
}

In this line of codes where it throws an error (cannot access a closed Stream): output.Write(ms.GetBuffer(), 0, (int)ms.Length);在这行代码中,它抛出错误(无法访问关闭的流): output.Write(ms.GetBuffer(), 0, (int)ms.Length);

Am I missing something here?我在这里错过了什么吗?

I just figure out what went wrong.我只是弄清楚出了什么问题。 For some reason once NPOI finish writing the workbook in a stream it closes it.出于某种原因,一旦 NPOI 在流中完成编写工作簿,它就会关闭它。

So to make the codes work we need to do this:所以为了使代码工作,我们需要这样做:

MemoryStream ms = new MemoryStream();
workbook.Write(ms);

var buffer = ms.ToArray();
var bytesRead = buffer.Length;

Then we can now pass it to the client:然后我们现在可以将它传递给客户端:

response.OutputStream.Write(buffer, 0, btyesRead);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM