0

How do I export 2 gridviews (GridView1 & GridView2) into 2 separate sheets in one MS Excel file with the click of 1 button? Currently, I'm able to export only 1 gridview to an Excel sheet which the filename is the same as the sheet name. But I would like to 2 gridviews into 2 separate sheets which I would like sheet name to be define/set by myself. Thanks

public void ExportGridToExcel()
{
      Response.Clear();
      Response.Buffer = true;
      Response.ClearContent();
      Response.ClearHeaders();
      Response.Charset = "";

      string FileName ="Export"+DateTime.Now+".xls";

      StringWriter strwritter = new StringWriter();
      HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);

      Response.Cache.SetCacheability(HttpCacheability.NoCache);
      Response.ContentType = "application/vnd.ms-excel";
      Response.AddHeader("Content-Disposition","attachment;filename=" + FileName);

      GridView1.GridLines = GridLines.Both;
      GridView1.HeaderStyle.Font.Bold = true;
      GridView1.RenderControl(htmltextwrtter);

      Response.Write(strwritter.ToString());
      Response.End();
}
James Boer
  • 321
  • 4
  • 9
  • 28

2 Answers2

0

//Edit my answer since there is only 1 export button: Take a look at this question:

firstly add these namespace:

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;

So basically you should have (or go ahead and make them) 2 DataTable (to bind to 2 gridviews): dt1 and dt2

Make a dataset and add 2 datatables to it

DataSet dataset = new DataSet();
        dataset.Tables.Add(dt1);
        dataset.Tables.Add(dt2);

then

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

to change worksheet name, I believe you can do:

currentSheet.Name = "your sheet name"
Community
  • 1
  • 1
Ronaldinho Learn Coding
  • 13,254
  • 24
  • 83
  • 110
0

you need to modifiy your code so that you will create a worksheet in the excel file and manually copy the data from grid to excel file and create this code as a function that takes grid,sheetname and sheetid like 1 ,2 and so on as arguments and then within button click event call it twice once for grid1 and once for grid2 with different sheetnames and sheet ids 1 and 2 respectively. the code for the function is as follows.

Write these two line of code in button click event and after that call the function twice once for each grid by passing excel app and workbook also as arguments.

     // creating Excel Application
     Microsoft.Office.Interop.Excel._Application app  = new Microsoft.Office.Interop.Excel.Application();

    // creating new WorkBook within Excel application
    Microsoft.Office.Interop.Excel._Workbook workbook =  app.Workbooks.Add(Type.Missing);

 public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook,GridView gridview,string SheetName,int sheetid)
 {  


        // creating new Excelsheet in workbook
         Microsoft.Office.Interop.Excel._Worksheet worksheet = null;                   

       // see the excel sheet behind the program
        app.Visible = true;

       // get the reference of first sheet. By default its name is Sheet1.
       // store its reference to worksheet
        worksheet = workbook.Sheets["Sheet"+ sheetid];
        worksheet = workbook.ActiveSheet;

        // changing the name of active sheet
        worksheet.Name = sheetname; 

        // storing header part in Excel
        for(int i=1;i<gridview.Columns.Count+1;i++)
        {
              worksheet.Cells[1, i] = gridview.Columns[i-1].HeaderText;
        }



        // storing Each row and column value to excel sheet
        for (int i=0; i < gridview.Rows.Count-1 ; i++)
        {
            for(int j=0;j<gridview.Columns.Count;j++)
            {
                worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Value.ToString();
            }
        }


        // save the application
        workbook.SaveAs("c:\\output.xls",Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive , Type.Missing, Type.Missing, Type.Missing, Type.Missing);

        // Exit from the application
      app.Quit();
    }
Ramesh Babu
  • 405
  • 4
  • 10
  • I want to export multiple gridview to one excel thus I believe ur codes will be exporting into 2 separate excel by calling it twice. Please advice thanks – James Boer Sep 29 '15 at 07:25
  • Sorry. I edited my answer. Hope this will solve the issue. – Ramesh Babu Sep 29 '15 at 07:42
  • I have added Microsoft.Offfice.Interop.Excel as reference but there is still error in one which is DataGridView that is underline missing type or namespace(missing reference) error. Please advice – James Boer Sep 29 '15 at 08:14
  • Please provide me the exact line where you are getting error and the error message – Ramesh Babu Sep 29 '15 at 08:17
  • public void ExportToExcel(Microsoft.Office.Interop.Excel._Application app, Microsoft.Office.Interop.Excel._Workbook workbook,DataGridView gridview,string SheetName,int sheetid) – James Boer Sep 29 '15 at 09:09
  • Sorry. It is not DataGridView and it is GridView – Ramesh Babu Sep 29 '15 at 10:26
  • THanks but I receive error at Value in worksheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Value.ToString(); I also assume to change gridview to my own gridview id name – James Boer Sep 30 '15 at 03:38
  • no need to change "gridview" to your gridview id. Here "gridview" is the parameter name in the function. if you provided different name to this parameter in the function then you need to use it in the place of "gridview" – Ramesh Babu Sep 30 '15 at 07:43
  • without the change the error still exist at Value (its underlined red) But isn't it weird that I have 2 gridviews but I need not specify my gridview id? in this case how would they know which gridview to which sheet? please advice thanks – James Boer Sep 30 '15 at 08:44
  • within the function, there is a parameter sheetname and this you will pass different name for different grids and based on that the data of two grid views will be in different sheets. What is the error message at Value? – Ramesh Babu Oct 01 '15 at 07:19
  • Error 7 'System.Web.UI.WebControls.TableCell' does not contain a definition for 'Value' and no extension method 'Value' accepting a first argument of type 'System.Web.UI.WebControls.TableCell' could be found (are you missing a using directive or an assembly reference?) – James Boer Oct 01 '15 at 07:29
  • In that case can I set a specific name for each sheet in the codes? please advice thanks alot – James Boer Oct 01 '15 at 07:29
  • Value must work. I was unable to determine why it is causing error to you. you will pass name for each sheet as argument for sheet name parameter. – Ramesh Babu Oct 01 '15 at 10:11
  • Hi there, sorry for the late reply but it work in createing the excel. However I received error in populate the data in thre excel. Hope you can help me out on this. Please refer to http://stackoverflow.com/questions/33115067/error-recevied-upon-exporting-of-2-gridviews-into-excel – James Boer Oct 14 '15 at 01:17