I have this code used on my application to export datagridview as csv file.It worked fine but csv doesnt show cell values correclty.See below images and I have pasted my code as well.What can I change on this code to fix this?
Here is the datagridview
This is the exported csv and it shows like this
Here is my code
- public void writeCSV(DataGridView gridIn, string outputFile)
- {
- //test to see if the DataGridView has any rows
- if (gridIn.RowCount > 0)
- {
- string value = "";
- DataGridViewRow dr = new DataGridViewRow();
- StreamWriter swOut = new StreamWriter(outputFile);
- //write header rows to csv
- for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
- {
- if (i > 0)
- {
- swOut.Write(",");
- }
- swOut.Write(gridIn.Columns[i].HeaderText);
- }
- swOut.WriteLine();
- //write DataGridView rows to csv
- for (int j = 0; j <= gridIn.Rows.Count - 2; j++)
- {
- if (j > 0)
- {
- swOut.WriteLine();
- }
- dr = gridIn.Rows[j];
- for (int i = 0; i <= gridIn.Columns.Count - 1; i++)
- {
- if (i > 0)
- {
- swOut.Write(",");
- }
- value = dr.Cells[i].Value.ToString();
- //replace comma's with spaces
- value = value.Replace(',', ' ');
- //replace embedded newlines with spaces
- value = value.Replace(Environment.NewLine, " ");
- swOut.Write(value);
- }
- }
- swOut.Close();
- }
- }

Nilesh ShahRank #42 · 34.2K reputationPosted May 31, 2017, 7:31 AM EDT
Nilesh ShahRank #42 · 34.2K reputationPosted Jun 1, 2017, 6:10 AM EDT
@RD Design
Guest UserRank #816 · 2.8K reputationPosted May 31, 2017, 4:50 AM EDT