Search code examples
c#asp.netexcelgridviewexport-to-excel

Generate Excel File using C# without Office tool


Currently I am using EPPlus Library mainly because EPPPlus doesn't need of office installed on End user pc but right now i've been specifying(insert) each row and column in to worksheet on this library.

I want to generate the excel file from GRIDVIEW data on server side without office tool.

So i need some other solution or Library file that could meet my expectation.

Thanks in advance.


Solution

  • I must admit that i don't understand why you can't use EPPlus with the GridView.

    You could use the DataSource of the GridView, for example if it's a DataTable:

    try {
        var pck = new OfficeOpenXml.ExcelPackage();
        var ws = pck.Workbook.Worksheets.Add("Sheet-Name");
        ws.Cells["A2"].LoadFromDataTable(tbl, false);
        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;  filename=FileName.xlsx");
        Response.BinaryWrite(pck.GetAsByteArray());
    } catch (Exception ex) {
        //log error
    }
    Response.End();