using Excel = Microsoft.Office.Interop.Excel;
SaveFileDialog sd = new SaveFileDialog();
sd.Filter = "Excel (*.xls)|*.xls";
sd.DefaultExt = "Excel files (*.xls)|(*.csv)";
sd.Title = "please select your NameA and Path";
if (sd.ShowDialog() == DialogResult.OK)
{
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
Excel.Range workSheet_range;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.ApplicationClass();
xlApp.Visible = true;
xlApp.UserControl = true;
System.Globalization.CultureInfo oldCI= System.Threading.Thread.CurrentThread.CurrentCulture;
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
xlWorkBook = xlApp.Workbooks.Add(1);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
xlWorkSheet.Cells[1, 1] = payGridView.Columns[0].HeaderText;
xlWorkSheet.Cells[1, 2] = payGridView.Columns[1].HeaderText;
xlWorkSheet.Cells[1, 3] = payGridView.Columns[3].HeaderText;
xlWorkSheet.Cells[1, 4] = payGridView.Columns[4].HeaderText;
workSheet_range = xlWorkSheet.get_Range(xlWorkSheet.Cells[1, 1],
xlWorkSheet.Cells[1, 4]);
workSheet_range.Font.Bold = true;
for (int i = 0; i <= this.payGridView.Rows.Count - 1; i++)
{
xlWorkSheet.Cells[i + 2, 1] = payGridView.Rows[i].Cells[0].Value.ToString();
xlWorkSheet.Cells[i + 2, 2] = payGridView.Rows[i].Cells[1].Value.ToString();
xlWorkSheet.Cells[i + 2, 3] = payGridView.Rows[i].Cells[3].Value.ToString();
xlWorkSheet.Cells[i + 2, 4] = payGridView.Rows[i].Cells[4].Value.ToString();
}
xlWorkSheet.Rows.AutoFit();
xlWorkSheet.Columns.AutoFit();
xlWorkBook.SaveAs(sd.FileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
GlobalClass.releaseObject(xlWorkSheet);
GlobalClass.releaseObject(xlWorkBook);
GlobalClass.releaseObject(xlApp);
MessageBox.Show("Your file is created successfully");
}