Shafiqq Aziz

Shafiqq Aziz

  • NA
  • 54
  • 12.2k

C# Export DataGridView to Excel

Nov 8 2017 10:27 PM
Hi all,
 
I'm using this (https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff) to create export to excel process.
 
I've encountered a problem where my first row of data does not exported to excel. And I think i'm not missing any line of codes provided in the tutorial. Can you guys help me out with this problem?
 
Here's my exported data.
 
 
 
And here's my codes. 
 
 
  1. private void ExportToExcel()  
  2.         {  
  3.             Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();  
  4.             Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);  
  5.             Microsoft.Office.Interop.Excel._Worksheet worksheet = null;  
  6.   
  7.             try  
  8.             {  
  9.                 worksheet = workbook.ActiveSheet;  
  10.   
  11.                 worksheet.Name = "Exported From DataGrid";  
  12.   
  13.                 int cellRowIndex = 1;  
  14.                 int cellColumnIndex = 1;  
  15.   
  16.                 for (int i = 0; i < dataGridView2.Rows.Count - 1; i++)  
  17.                 {  
  18.                     for (int j = 0; j < dataGridView2.Columns.Count; j++)  
  19.                     {  
  20.                         if (cellRowIndex == 1)  
  21.                         {  
  22.                             worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView2.Columns[j].HeaderText;  
  23.                         }  
  24.                         else  
  25.                         {  
  26.                             worksheet.Cells[cellRowIndex, cellColumnIndex] = dataGridView2.Rows[i].Cells[j].Value.ToString();  
  27.                         }  
  28.                         cellColumnIndex++;  
  29.                     }  
  30.                     cellColumnIndex = 1;  
  31.                     cellRowIndex++;  
  32.                 }  
  33.   
  34.                 SaveFileDialog saveDialog = new SaveFileDialog();  
  35.                 saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx";  
  36.                 saveDialog.FilterIndex = 1;  
  37.   
  38.                 if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  39.                 {  
  40.                     workbook.SaveAs(saveDialog.FileName);  
  41.                     MessageBox.Show("Export Successful!");  
  42.                 }  
  43.             }  
  44.               
  45.             catch (System.Exception ex)  
  46.             {  
  47.                 MessageBox.Show(ex.Message);  
  48.             }  
  49.             finally  
  50.             {  
  51.                 excel.Quit();  
  52.                 workbook = null;  
  53.                 excel = null;  
  54.             }  
  55.         }  

Answers (4)