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:
- private void btnExport_Click(object sender, EventArgs e)
- {
-
- if (dataGridView1.Rows.Count == 0)
- {
- return;
- }
- StringBuilder sb = new StringBuilder();
-
- string columnsHeader = ",".TrimStart(',').TrimEnd(',') + ('"');
- for (int i = 0; i < dataGridView1.Columns.Count; i++)
- {
- columnsHeader += dataGridView1.Columns[i].Name +'"' + ',' + '"';
- }
- sb.Append(columnsHeader + Environment.NewLine);
-
- foreach (DataGridViewRow dgvRow in dataGridView1.Rows)
- {
-
- if (!dgvRow.IsNewRow)
- {
- for (int c = 0; c < dgvRow.Cells.Count; c++)
- {
-
- sb.Append (dgvRow.Cells[c].Value + ","+ ""+ "".TrimEnd(','));
- }
-
- sb.Append(Environment.NewLine);
- }
- }
-
- SaveFileDialog sfd = new SaveFileDialog();
- sfd.Filter = "CSV files (*.csv)|*.csv";
- if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
-
- using (System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName, false))
- {
-
- sw.WriteLine(sb.ToString());
- }
- }
I would appreciate all help, Thanks.
-Matti