Friday, 6 September 2013

Export data DataGridView 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);
}

No comments:

Post a Comment