Matti Tiira

Matti Tiira

  • NA
  • 46
  • 9.2k

Extra rows when exporting datagridview as csv

Mar 29 2019 5:53 AM
Hi!
 
I have a program that can export datagridview to csv.
All works well and all but one problem has occured.
The created csv file has two extra rows that are empty and they are causing me some trouble.
How can I get rid of them when exporting. Trimming them of in notepad is not really an option.
 
My code for the export looks like this:
  1. private void btnExport_Click(object sender, EventArgs e)  
  2. {  
  3. // Don't save if no data is returned  
  4. if (dataGridView1.Rows.Count == 0)  
  5. {  
  6. return;  
  7. }  
  8. StringBuilder sb = new StringBuilder();  
  9. sb.AppendLine(string.Join(",", dataGridView1.Columns.Cast().Select(x => $"\"{x.Name}\"")));  
  10. foreach (DataGridViewRow row in dataGridView1.Rows)  
  11. {  
  12. if (!row.IsNewRow)  
  13. {  
  14. sb.AppendLine(string.Join(",", row.Cells.Cast().Select(c => $"\"{c.Value ?? ""}\"")));  
  15. }  
  16. }  
  17. // Load up the save file dialog with the default option as saving as a .csv file.  
  18. SaveFileDialog sfd = new SaveFileDialog();  
  19. sfd.Filter = "CSV files (*.csv)|*.csv";  
  20. if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  21. {  
  22. // If they've selected a save location...  
  23. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))  
  24. {  
  25. // Write the stringbuilder text to the the file.  
  26. sw.WriteLine(sb.ToString());  
  27. }  
  28. }  
All help is appreciated, Thanks.
 
-Matti 

Answers (4)