Timur Lenk

Timur Lenk

  • NA
  • 18
  • 3.5k

C# GridView export to Excel

Oct 20 2015 11:39 AM
Hi Guys,
 
Please could you help me.
 
I try to export from DataGridView to Excel.
 
This is my code for the "Export" button:
 

        private void pb_export_Click(object sender, EventArgs e)
        {
            saveFileDialog1.InitialDirectory = "C:";
            saveFileDialog1.Title = "Export to excel as";
            saveFileDialog1.FileName = "";
            saveFileDialog1.Filter = "Excel Files (2003 *.xls)|*.xls|Excel Files (2007 *.xlsx)|*.xlsx";
            if (saveFileDialog1.ShowDialog() != DialogResult.Cancel)
            {
                Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
                ExcelApp.Application.Workbooks.Add(Type.Missing);
                ExcelApp.Columns.ColumnWidth = 10;

                for (int i = 0; i < dgw_data.Rows.Count; i++)
                {
                    DataGridViewRow row = dgw_data.Rows[i];
                    for (int j = 0; j < row.Cells.Count; j++)
                    {
                        ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString();
                    }
                }

                ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog1.FileName.ToString());
                ExcelApp.ActiveWorkbook.Saved = true;
                ExcelApp.Quit();
            }
        }

 

 

The output Excel file doesn't containing values:
 
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=0 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=0 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=1 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=1 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=2 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=2 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=3 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=3 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=4 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=4 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=5 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=5 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=6 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=6 }
DataGridViewTextBoxCell { ColumnIndex=0, RowIndex=7 } DataGridViewTextBoxCell { ColumnIndex=1, RowIndex=7 }
 
 
Your help would be great.
 
 
Thanks,
 
Timur

 


Answers (4)