Matti Tiira

Matti Tiira

  • NA
  • 46
  • 9.3k

Csv exporting with double quotes and commas

Mar 29 2019 2:59 AM
Hi!
 
I have a program which with I can upload a csv to datagridview and modify it.
 
I want to export the datagridview info as a csv file and I would want it to look the same as it was imported.
 
The imported csv file looks like this:
 
"Nro","Tyyppi","Yks","Ktp","Kustpk","Alue","Laatu","Koodi","Selite","Lisatietoja"
"110","VARASTO","24.30","A12","","","2/ ","","",""
"111","OPETUSKE","55.80","A54","","","3/ ","","",""
"112","LUOKKA","57.40","A54","","","3/ ","","",""
"113","LUOKKA","55.80","A54","","","3/ ","","",""
"114","OPETUSKE","56.70","A54","","","3/ ","","",""
"115","PIENRY","31.80","A52","","","3/ ","","",""
"116","LUOKKA","56.70","A54","","","3/ ","","",""
 
The first row is headerlabels and the rest is the info that is going to be modified.
 
The exported csv file looks like this:
 
"Nro","Tyyppi","Yks","Ktp","Kustpk","Alue","Laatu","Koodi","Selite","Lisatietoja","
110,VARASTO,24.30,A12,,,2/ ,,,,
111,OPETUSKE,55.80,A54,,,3/ ,,,,
112,LUOKKA,57.40,A54,,,3/ ,,,,
113,LUOKKA,55.80,A54,,,3/ ,,,,
114,OPETUSKE,56.70,A54,,,3/ ,,,,
115,PIENRY,31.80,A52,,,3/ ,,,,
116,LUOKKA,56.70,A54,,,3/ ,,,,
 
And 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. // Column headers  
  10. string columnsHeader = ",".TrimStart(',').TrimEnd(',') + ('"');  
  11. for (int i = 0; i < dataGridView1.Columns.Count; i++)  
  12. {  
  13. columnsHeader += dataGridView1.Columns[i].Name +'"' + ',' + '"';  
  14. }  
  15. sb.Append(columnsHeader + Environment.NewLine);  
  16. // Go through each cell in the datagridview  
  17. foreach (DataGridViewRow dgvRow in dataGridView1.Rows)  
  18. {  
  19. // Make sure it's not an empty row.  
  20. if (!dgvRow.IsNewRow)  
  21. {  
  22. for (int c = 0; c < dgvRow.Cells.Count; c++)  
  23. {  
  24. // Append the cells data followed by a comma to delimit.  
  25. sb.Append (dgvRow.Cells[c].Value + ",""""".TrimEnd(','));  
  26. }  
  27. // Add a new line in the text file.  
  28. sb.Append(Environment.NewLine);  
  29. }  
  30. }  
  31. // Load up the save file dialog with the default option as saving as a .csv file.  
  32. SaveFileDialog sfd = new SaveFileDialog();  
  33. sfd.Filter = "CSV files (*.csv)|*.csv";  
  34. if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)  
  35. {  
  36. // If they've selected a save location...  
  37. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))  
  38. {  
  39. // Write the stringbuilder text to the the file.  
  40. sw.WriteLine(sb.ToString());  
  41. }  
  42. }  
I would appreciate all help, Thanks.
-Matti

Answers (3)