Search code examples
c#datagridviewexport-to-excel

Export data DataGridView to Excel


I'm creating a class to export data from DataGridView to Excel file. When I invoke the method I got an empty excel sheet. However it does work when I insert directly the method inside the code without using a class.

Any idea why this class doesn't work.

class ExportToExcel
{
       public Microsoft.Office.Interop.Excel.Application ExcelApp =  new Microsoft.Office.Interop.Excel.Application();
       public Microsoft.Office.Interop.Excel._Workbook ExcelBook;
       public Microsoft.Office.Interop.Excel._Worksheet ExcelSheet;
       DataGridView dt = new DataGridView();

       public  DataGridView Dt { set { this.dt = value; } }


       public Microsoft.Office.Interop.Excel.Application exportToExcel(DataGridView dt)
        {
        int i = 0;
        int j = 0;



        ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1);
        ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet;
        //export header
        for (i = 1; i <= this.dt.Columns.Count; i++)
        {
            ExcelSheet.Cells[1, i] = this.dt.Columns[i - 1].HeaderText;
        }

        //export data
        for (i = 1; i <= this.dt.RowCount; i++)
        {
            for (j = 1; j <= dt.Columns.Count; j++)
            {
                ExcelSheet.Cells[i + 1, j] = dt.Rows[i - 1].Cells[j - 1].Value;
            }
        }


            ExcelApp.Visible = true;
            ExcelSheet = null;
            ExcelBook = null;
            ExcelApp = null;

         return ExcelApp;

    }
}

private void exportToExcel_Click(object sender, EventArgs e)
    {

        ExportToExcel ex = new ExportToExcel();
        ex.exportToExcel(dtReport2);
    }

Solution

  • exportToExcel(DataGridView dt)

    It looks like your method is referring both to this.dt (class variable) and a local version of dt (the one you pass into the method as a parameter.)

    Based on your code - the class version of dt is never being set to anything.

    I'm not sure exactly how you want your class to work, but you may want to consider setting dt and not passing another gridview into your exportToExcel method.

     private void exportToExcel_Click(object sender, EventArgs e)
    {
    
        ExportToExcel ex = new ExportToExcel();
        ex.dt = dtReport2; // set the public class variable here
        ex.exportToExcel(); // removed the datagrid from your parameter in the exportToExcel() method
    }