Export GridView to multiple Excel sheet

后端 未结 4 678
北荒
北荒 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

    I agree with @Andrew Burgess and have implemented his code into one of my projects. Just for the record theres a few small errors in the code which will cause some COM Exceptions. The corrected code is below (the issue was that Excel numbers sheets, rows, columns from 1 to n not from zero).

    using Excel = Microsoft.Office.Interop.Excel;
    using System.Reflection;
    using System.IO;
    
            //Print using Ofice InterOp
            Excel.Application excel = new Excel.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);
                    }
    
                    //NOTE: Excel numbering goes from 1 to n
                    var currentSheet = (Excel._Worksheet)workbook.Sheets[i + 1]; 
    
                    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+1, x+1] = dataset.Tables[i].Rows[y].ItemArray[x];
                        }
                    }
            }
    
            string outfile = @"C:\APP_OUTPUT\EXCEL_TEST.xlsx";
    
            workbook.SaveAs( outfile, Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlNoChange,
                            Type.Missing, Type.Missing, Type.Missing, Type.Missing,
                            Type.Missing);
    
            workbook.Close();
            excel.Quit();
    

提交回复
热议问题