This is the code snippet for creating excel file with the details of grid view in windows application:
public void generateExcel()
{
string GivenFileName = null;
if (gvData.Rows.Count > 0)
{
DialogResult Result = saveFileDialog1.ShowDialog();//Show the dialog to save the file.
if ((Result == DialogResult.OK) && (saveFileDialog1.FileName.Length > 0))
{
GivenFileName = saveFileDialog1.FileName;
Microsoft.Office.Interop.Excel.Application ExcelApp = new
Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 20;
// Storing header part in Excel
for (int i = 1; i < gvData.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = gvData.Columns[i - 1].HeaderText;
}
for (int i = 0; i < gvData.Rows.Count; i++)
{
for (int j = 0; j < gvData.Columns.Count; j++)
{
ExcelApp.Cells[i + 2, j + 1] = gvData.Rows[i].Cells[j].Value.ToString();
}
}
string location = GivenFileName;
ExcelApp.ActiveWorkbook.SaveCopyAs(location + ".xlsx");
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("Details saved in excel !.");
}
}
else
MessageBox.Show("Nothing to upload !.");
} 