In my application, there is requirement to export datagridview into Excel.
I am using the following source code. I wanted expert advice on following questions.
Is my code is correct or not? because i am not getting any file saved at the selected path.
Is there any performance issue while exporting data from grid, because there could be as many as data available in grid?
- I am using Namespace "Microsoft.Office.Interop.Excel", not sure if that is right?
private void btnSaveResult_Click(object sender, EventArgs e)
{
try
{
if (this.saveFileDialog.ShowDialog() == DialogResult.OK)
{
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
ExcelApp.Application.Workbooks.Add(Type.Missing);
ExcelApp.Columns.ColumnWidth = 30;
for (int i = 0; i < grdResult.Rows.Count; i++)
{
DataGridViewRow row = grdResult.Rows[i];
for (int j = 0; j < row.Cells.Count; j++)
{
ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
}
}
ExcelApp.ActiveWorkbook.Saved = true;
ExcelApp.Quit();
MessageBox.Show("The Save button was clicked or the Enter key was pressed" + "\nThe file would have been saved as " + this.saveFileDialog.FileName);
}
else MessageBox.Show("The Cancel button was clicked or Esc was pressed");
}
catch (Exception ex)
{
MessageBox.Show("Cancelled Save Operation");
this.Close();
}
}
Try Following class
And use it as below
Remove labels if you do not want them.. make changes as per your need.
Implementation weaknesses: - you don't free resouces you use; - you export items one by one (it's extremely slow), there's range designed for that, where you can set object[,] (of boxed int, strings, ...); - you don't handle formatting of text (Excel's decisions about format are not right), - you mix view and export logic.
get handle to workbook whe you add, and call Workbook.SaveCopyAs(filePath);