Exporting DataGridView into Excel

Exporting DatagridView into Excel



Call this function by passing Datagridview parameter into this function




public void exporttoexcel(DataGridView grid)
{
Microsoft.Office.Interop.Excel.ApplicationClass excelSheet = new Microsoft.Office.Interop.Excel.ApplicationClass();
excelSheet.Application.Workbooks.Add(true);
int columnIndex = 0;
//Columns Heading of Datagridview
foreach (DataGridViewColumn column in grid.Columns)
{
columnIndex++;
excelSheet.Cells[1, columnIndex] = column.HeaderText;
}
int rowIndex = 0;
//get all rows by column wise
foreach (DataGridViewRow row in grid.Rows)
{
rowIndex++;
columnIndex = 0;
foreach (DataGridViewColumn column in grid.Columns)
{
columnIndex++;
excelSheet.Cells[rowIndex + 1, columnIndex] = row.Cells[column.Name].FormattedValue;
}
}
excelSheet.Visible = true;
Microsoft.Office.Interop.Excel.Worksheet workSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheet.ActiveSheet;
workSheet.Activate();
}


Comments



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: