简体   繁体   中英

Outputing workbook create in NPOI library using custom FileResult

I created an ASP.NET Mvc custom FileResult that will export a workbook( .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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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