Exporting datagridview to csv file

  • Thread starter Thread starter okrus
  • Start date Start date
O

okrus

Guest
I'm trying to export my datagridview to Excel csv file with a button click event. The export works fine, but the file is not saved in the right format. I need it to be saved as "CSV (Comma delimited) (*.csv)", but it saves as "Excel-workbook (*.xlsx)". What am I doing wrong?


private void export_Btn_Click(object sender, EventArgs e)
{
saveFileDialog.InitialDirectory = "C";
saveFileDialog.Title = "Save as excel file";
saveFileDialog.FileName = "";
saveFileDialog.Filter = "CSV (Comma delimited)|*.csv";
if (saveFileDialog.ShowDialog() != DialogResult.Cancel)
{
Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application();
ExcelApp.Application.Workbooks.Add(Type.Missing);

ExcelApp.Columns.ColumnWidth = 20;
//header
for (int i = 1; i < dataGridView3.Columns.Count + 1; i++)
{
ExcelApp.Cells[1, i] = dataGridView3.Columns[i - 1].HeaderText;
}
//storing each row and column value for excel sheet
for (int i = 0; i < dataGridView3.Rows.Count; i++)
{
for (int j = 0; j < dataGridView3.Columns.Count; j++)
{
if (dataGridView3.Rows.Cells[j].Value != null)
{
ExcelApp.Cells[i + 2, j + 1] = dataGridView3.Rows.Cells[j].Value.ToString();
}

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

Continue reading...
 
Back
Top