Export GridView to multiple Excel sheet

后端 未结 4 681
北荒
北荒 2020-11-29 12:34

I have two Gridview in my Web application.I need ,while clicking the (ExcelExpot) button the values to be Export in Excel Accordingly Sheet1 and Sheet2.

  pr         


        
4条回答
  •  死守一世寂寞
    2020-11-29 13:06

    Doing this with EPPlus is a piece of cake. No Interop assemblies required and literally 2 lines of code do all the magic:

    ws.Cells["A1"].LoadFromDataTable(dt1, true);
    ws2.Cells["A1"].LoadFromDataTable(dt2, true);
    

    Complete code:

    protected void ExportExcel_Click(object sender, EventArgs e)
    {
    
         //LinQ Query for dt2
        var query = (from c in dt.AsEnumerable()
        select new {id= c.Field("id"),name=c.Field("name"),city=c.Field("city")}) ;
        DataTable dt2 = new DataTable();
        dt2=query.CopyToDatatable();
    
        //DataTable dt1
        DataTable dt1 =new DataTable();
        mySqlDataAdapter.Fill(dt1);
    
        using (ExcelPackage pck = new ExcelPackage())
        {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Page 1");
            ExcelWorksheet ws2 = pck.Workbook.Worksheets.Add("Page 2");
    
            ws.Cells["A1"].LoadFromDataTable(dt1, true);
            ws2.Cells["A1"].LoadFromDataTable(dt2, true);
    
            //Write it back to the client
            Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
            Response.BinaryWrite(pck.GetAsByteArray());
            Response.Flush();
            Response.End();
        }
    }
    

    Note that I copied and paste it your code to gather the data. I expect these lines to produce a DataTable.

提交回复
热议问题