I have 10k rows and 15 column in my data grid view. I want to export this data to an excel sheet o button click. I have already tried with the below code.
pr
In my opinion this is the easiest and instantly working method of exporting datagridview.
try
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.xlsx)|*.xlsx";
sfd.FileName = "ProfitLoss.xlsx";
if (sfd.ShowDialog() == DialogResult.OK)
{
DataTable dts = new DataTable();
for (int i = 0; i < grdProfitAndLoss.Columns.Count; i++)
{
dts.Columns.Add(grdProfitAndLoss.Columns[i].Name);
}
for (int j = 0; j < grdProfitAndLoss.Rows.Count; j++)
{
DataRow toInsert = dts.NewRow();
int k = 0;
int inc = 0;
for (k = 0; k < grdProfitAndLoss.Columns.Count; k++)
{
if (grdProfitAndLoss.Columns[k].Visible == false) { continue; }
toInsert[inc] = grdProfitAndLoss.Rows[j].Cells[k].Value;
inc++;
}
dts.Rows.Add(toInsert);
}
dts.AcceptChanges();
ExcelUtlity obj = new ExcelUtlity();
obj.WriteDataTableToExcel(dts, "Profit And Loss", sfd.FileName, "Profit And Loss");
MessageBox.Show("Exported Successfully");
}
}
catch (Exception ex)
{
}
This answer is for the first question, why it takes so much time and it offers an alternative solution for exporting the DataGridView to Excel.
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to export large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Interop saves Excel files in XLS file format (old Excel 97-2003 file format) and the support for Office 2003 has ended. Microsoft Excel released XLSX file format with Office 2007 and recommends the usage of OpenXML SDK instead of Interop. But XLSX files are not really so fast and doesn’t handle very well large Excel files because they are based on XML file format. This is why Microsoft also released XLSB file format with Office 2007, file format that is recommended for large Excel files. It is a binary format. So the best and fastest solution is to save XLSB files.
You can use this C# Excel library to save XLSB files, but it also supports XLS and XLSX file formats.
See the following code sample as alternative of exporting DataGridView to Excel:
// Create a DataSet and add the DataTable of DataGridView
DataSet dataSet = new DataSet();
dataSet.Tables.Add((DataTable)dataGridView);
//or ((DataTable)dataGridView.DataSource).Copy() to create a copy
// Export Excel file
ExcelDocument workbook = new ExcelDocument();
workbook.easy_WriteXLSBFile_FromDataSet(filePath, dataSet,
new EasyXLS.ExcelAutoFormat(EasyXLS.Constants.Styles.AUTOFORMAT_EASYXLS1),
"Sheet1");
If you also need to export the formatting of the DataGridView check this code sample on how to export datagridview to Excel in C#.