Click here to Skip to main content
15,896,606 members

Saving Data From DataGrid to Excel, How can I Optimise the code to make the process faster ?

Peter Bamuhigire asked:

Open original thread
I have a windows application in C#. One of the function it has is to extract data from the Database and save it in excel so It can be sent to headquarters to be imported into their database.

The program works fine and does as is required, However it takes a long time to save the data to excel, It extracts from the Database just fine and loads the data into a data grid view, but saving from the datagridview to Excel takes long, sometimes up to 7 minutes. How can I speed up this process ?

Also, why does the Excel process keep running ? Isn't EXL.Quit() as in my code, supposed to kill the process ?

Below is the code I am using to save from DataGridView to Excel.

C#
private void btnSavetoExcel_Click(object sender, EventArgs e)
       {
            //Save Extracted Report to Microsoft Excel

           //If No Data is there in the grid
           if (gridExtractReport.RowCount < 1)
           {
               MessageBox.Show("No Data to Save.\r\nPlease Try Again",
            "Distributor Sales Management System", MessageBoxButtons.OK, MessageBoxIcon.Error);
               return;
           }

           //New Excel Application
           ExcelSpreadsheet.Application EXL = new ExcelSpreadsheet.Application();

           //data table
           DataSet dset = new DataSet();
           dset.Tables.Add();

           //add columns to table
           for (int x = 0; x <= (gridExtractReport.ColumnCount - 1); x++)
           {
               dset.Tables[0].Columns.Add(gridExtractReport.Columns[x].HeaderText);
           }

           //datarow
           DataRow drow1;

           //add rows to table
           for (int x = 0; x <= (gridExtractReport.RowCount - 1); x++)
           {
               drow1 = dset.Tables[0].NewRow();

               for (int y = 0; y <= (gridExtractReport.ColumnCount - 1); y++)
               {
                   drow1[y] = gridExtractReport.Rows[x].Cells[y].Value;
               }

               dset.Tables[0].Rows.Add(drow1);

           }

           //Create Worksheet
           ExcelSpreadsheet.Workbook Wbook;
           Wbook = EXL.Workbooks.Add(ExcelSpreadsheet.XlWBATemplate.xlWBATWorksheet);
           ExcelSpreadsheet.Worksheet WSheet = (ExcelSpreadsheet.Worksheet)Wbook.ActiveSheet;
           WSheet.Cells.Font.Size = 10;
           WSheet.Cells.Font.Name = "Arial";

           //Tables and Columns
           DataTable dt = dset.Tables[0];
           DataColumn dc = new DataColumn();
           //DataRow dr = new DataRow();
           int colIndex = 0, rowIndex = 0;
           foreach (DataColumn dcol in dt.Columns)
           {
               colIndex = colIndex + 1;
               EXL.Cells[1, colIndex] = dcol.ColumnName;
           }
           foreach (DataRow drow in dt.Rows)
           {
               rowIndex = rowIndex + 1;
               colIndex = 0;

               foreach (DataColumn dcol in dt.Columns)
               {
                   colIndex = colIndex + 1;
                   EXL.Cells[rowIndex + 1, colIndex] = drow[dcol.ColumnName];

               }

           }

           saveReport.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
           saveReport.Filter = "Microsoft Excel | *.xls";
           saveReport.FileName = "DSDPD2extract";

           //Format Column Titles
           WSheet.get_Range("A1:Q1", Type.Missing).BorderAround(ExcelSpreadsheet.XlLineStyle.xlContinuous,ExcelSpreadsheet.XlBorderWeight.xlThin,ExcelSpreadsheet.XlColorIndex.xlColorIndexAutomatic,System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black));
           WSheet.get_Range("A1:Q1", Type.Missing).Borders[Microsoft.Office.Interop.Excel.XlBordersIndex.xlInsideVertical].Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Black);
           WSheet.get_Range("A1:Q1", Type.Missing).ColumnWidth = 13.29;
           WSheet.get_Range("A1:Q1", Type.Missing).HorizontalAlignment = ExcelSpreadsheet.XlHAlign.xlHAlignCenter;

           if (saveReport.ShowDialog() == DialogResult.OK)
           {
               try
               {
                   WSheet.Name = "DSDPD2extract";
                   WSheet.get_Range("A1:Q1", Type.Missing).Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.FromArgb(192, 192, 192));

                   EXL.ActiveWorkbook.SaveAs(saveReport.FileName, ExcelSpreadsheet.XlFileFormat.xlExcel8, Type.Missing, Type.Missing, false, false, ExcelSpreadsheet.XlSaveAsAccessMode.xlShared, ExcelSpreadsheet.XlSaveConflictResolution.xlLocalSessionChanges, false, Type.Missing, Type.Missing, false);
               }
               catch (Exception)
               {
                   MessageBox.Show("Error Exporting Report.\r\nPlease Try Again", "Distributor Sales Management System", MessageBoxButtons.OK, MessageBoxIcon.Error);
                   return; // if Command Fails
               }
               MessageBox.Show("Report Succesfully Saved !", "Distributor Sales Management System", MessageBoxButtons.OK, MessageBoxIcon.Information);
           }

           EXL.ActiveWorkbook.Close(false, null, null);
           EXL.Quit();
       }
Tags: C#, Microsoft Office, Microsoft Excel, DataGridView

Plain Text
ASM
ASP
ASP.NET
BASIC
BAT
C#
C++
COBOL
CoffeeScript
CSS
Dart
dbase
F#
FORTRAN
HTML
Java
Javascript
Kotlin
Lua
MIDL
MSIL
ObjectiveC
Pascal
PERL
PHP
PowerShell
Python
Razor
Ruby
Scala
Shell
SLN
SQL
Swift
T4
Terminal
TypeScript
VB
VBScript
XML
YAML

Preview



When answering a question please:
  1. Read the question carefully.
  2. Understand that English isn't everyone's first language so be lenient of bad spelling and grammar.
  3. If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.
  4. Don't tell someone to read the manual. Chances are they have and don't get it. Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.
Please note that all posts will be submitted under the http://www.codeproject.com/info/cpol10.aspx.



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900