// here is my code //
// also want a text align centre when the data is imported to excel this code is working fine for me but the problem is that its saveing the file to fix location which i have hardcoded //
private void btnexcel_Click(object sender, EventArgs e)
{
ExportToExcel(dataGridView1, "StudentDetails");
}
public void ExportToExcel(DataGridView gridviewID, string excelFilename)
{
Microsoft.Office.Interop.Excel.Application objexcelapp = new Microsoft.Office.Interop.Excel.Application();
objexcelapp.Application.Workbooks.Add(Type.Missing);
objexcelapp.Columns.ColumnWidth = 24;
for (int i = 1; i < gridviewID.Columns.Count + 1; i++)
{
objexcelapp.Cells[1, i] = gridviewID.Columns[i - 1].HeaderText;
}
/*For storing Each row and column value to excel sheet*/
for (int i = 0; i < gridviewID.Rows.Count; i++)
{
for (int j = 0; j < gridviewID.Columns.Count; j++)
{
if (gridviewID.Rows[i].Cells[j].Value != null)
{
objexcelapp.Cells[i + 2, j + 1] = gridviewID.Rows[i].Cells[j].Value.ToString();
}
}
}
MessageBox.Show("Your excel file exported successfully at D:\\" + excelFilename + ".xlsx");
objexcelapp.ActiveWorkbook.SaveCopyAs("D:\\Matrix E Solution Projects\\ExcelSavedFiles" + excelFilename + ".xlsx");
objexcelapp.ActiveWorkbook.Saved = true;
//objexcelapp.Cells.Style.Fill.PatternType = ExportToExcel.Solid;
}