Export GridView to multiple Excel sheet

后端 未结 4 690
北荒
北荒 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:15

    You'll need to create the workbook, add more sheets if needed (defaults with three), and then fill out the cells.

    Top of the file:

    using Excel=Microsoft.Office.Interop.Excel;
    

    And then the main code for generating the Excel file

    Excel.Application excel = new Application();
    
    var workbook = (Excel._Workbook) (excel.Workbooks.Add(Missing.Value));
    
    for (var i = 0; i < dataset.Tables.Count; i++)
    {
        if (workbook.Sheets.Count <= i)
        {
            workbook.Sheets.Add(Type.Missing, Type.Missing, Type.Missing, 
                                Type.Missing);
        }
    
        var currentSheet = (Excel._Worksheet)workbook.Sheets[i];
        for (var y = 0; y < dataset.Tables[i].Rows.Count; y++)
        {
            for (var x = 0; x < dataset.Tables[i].Rows[y].ItemArray.Count(); x++)
            {
                currentSheet.Cells[y, x] = dataset.Tables[i].Rows[y].ItemArray[x];
            }
        }
    }
    
    workbook.SaveAs("C:\\Temp\\book.xlsx", Type.Missing, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, 
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
                    Type.Missing);
    
    workbook.Close();
    excel.Quit();
    
    Response.WriteFile(C:\\Temp\\book.xlsx");
    

    Don't know exactly if this will work, but it should get you in the right direction

    (also: Type.Missing and Missing.Value come from the namespace System.Reflection, just FYI)

提交回复
热议问题