I got the solution now. Please let me know if there are any issues with this code:
public static void ExportGridViewToExcel(DataGridView gridview)
{
try
{
System.Globalization.CultureInfo oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
Microsoft.Office.Interop.Excel.Workbook wb = null;
Microsoft.Office.Interop.Excel._Worksheet wSheet = null;
object misValue = System.Reflection.Missing.Value;
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
wb = ExcelApp.Workbooks.Add(Missing.Value);
wSheet = wb.Sheets.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 20;
ExcelApp.Visible = false;
for (int i = 1; i < gridview.Columns.Count + 1; i++)
{
wSheet.Cells[1, i] = gridview.Columns[i - 1].HeaderText;
}
for (int i = 0; i < gridview.Rows.Count - 1; i++)
{
for (int j = 0; j < gridview.Columns.Count; j++)
{
wSheet.Cells[i + 2, j + 1] = gridview.Rows[i].Cells[j].Value.ToString();
}
}
ExcelApp.Visible = true;
string fileName = SaveAs();
wSheet.SaveAs(fileName);
wb.Saved = true;
wb.Close();
ExcelApp.Quit();
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
ExcelDocViewer(fileName);
}
catch (Exception ex)
{
}
}
public static void ExcelDocViewer(string fileName)
{
try
{
System.Diagnostics.Process.Start(fileName);
}
catch { }
}
public static string SaveAs()
{
string FileName = null;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = Environment.GetFolderPath
(Environment.SpecialFolder.Personal);
saveFileDialog.Filter = "Excel Files (*.xlsx)|*.xlsx";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
FileName = saveFileDialog.FileName;
}
return FileName;
}