using Microsoft.Office.Interop.Excel;
//Create a Button btnExport on your form and write following code on its Click Event
private void btnExport_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
DialogResult drSaveFile = sfd.ShowDialog();
try
{
if (drSaveFile == System.Windows.Forms.DialogResult.OK)
{
ApplicationClass ExcelApp = new ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
//ExcelApp.ActiveWorkbook.FileFormat = XlFileFormat.xlExcel8;
// Change properties of the Workbook
ExcelApp.Columns.ColumnWidth = 20;
// Storing header part in Excel
for (int i = 1; i < datagridview.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = datagridview.Columns[i - 1].HeaderText;
}
// Storing Each row and column value to excel sheet
for (int i = 0; i < datagridview.Rows.Count; i++)
{
for (int j = 0; j < datagridview.Columns.Count; j++)
{
if (j == 2 || j == 5)
{
ExcelApp.Cells[i + 2, j + 1] = "'" + datagridview.Rows[i].Cells[j].Value.ToString();
}
else
{
ExcelApp.Cells[i + 2, j + 1] = datagridview.Rows[i].Cells[j].Value.ToString();
}
}
}
//Save Copy by giving file Path
//ExcelApp.ActiveWorkbook.SaveCopyAs("C:\\" + FileName);
//OR using SaveFileDialog
ExcelApp.ActiveWorkbook.SaveCopyAs(sfd.FileName);
//OR even you can use SaveAs function
//ExcelApp.ActiveWorkbook.SaveAs(sfd.FileName, XlFileFormat.xlExcel8, null, null, null,
// null, XlSaveAsAccessMode.xlShared, null, null, null, null, null);
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR: " + ex.Message);
}
}In this Code Snippet we will see how to Export DataGridView to Excel Sheet in C#
