Click here to Skip to main content
15,888,212 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How to format the CSV file, coz i got problem in opening it on excel, E.g. Price (integer) separates, for Example Php 7,100 must be in one cell , but it showed in 2 cells, like 7 100, how to fix it



C#
// create one file gridview.csv in writing mode using streamwriter
StreamWriter sw = new StreamWriter("gridview.csv");
// now add the gridview header in csv file suffix with "," delimeter except last one
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
    sw.Write(dataGridView1.Columns[i].HeaderText);
    if (i != dataGridView1.Columns.Count)
    {
        sw.Write(",");
    }
}
// add new line
sw.Write(sw.NewLine);
// iterate through all the rows within the gridview
foreach (DataGridViewRow dr in dataGridView1.Rows)
{
    // iterate through all colums of specific row
    for (int i = 0; i < dataGridView1.Columns.Count; i++)
    {
        // write particular cell to csv file
        sw.Write(dr.Cells[i].Value +",");
 
        if (i != dataGridView1.Columns.Count)
        {
           // sw.Write(",");
        }
    }
    // write new line
    sw.Write(sw.NewLine);
}
// flush from the buffers.
sw.Flush();
// closes the file
sw.Close();
Posted

1 solution

As it is a comma delimited file you cannot put in commas that are not meant as delimiters: https://en.wikipedia.org/wiki/Comma-separated_values[^]

The easiest way (but not the only way) is to remove them as you are creating the csv: https://social.msdn.microsoft.com/Forums/en-US/7c293b41-e26d-4d46-9b26-d95cdc8d30a2/c-streamwriter-how-to-ignore-reading-comma-characters?forum=csharplanguage[^]
 
Share this answer
 
v2
Comments
Rencyrence 28-Oct-15 21:25pm    
thanks for the help
[no name] 29-Oct-15 1:01am    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900