I export the datagridview records in csv file using code :

using (StreamWriter myFile = new StreamWriter(filename, false, Encoding.Default))
{
        string sHeaders = "";
        for (int j = 0; j < dGV.Columns.Count; j++)
        {
             if (dGV.Columns[j].Visible)
             {
                 sHeaders = sHeaders.ToString() + dGV.Columns[j].HeaderText + ", "; 
             }
        }
        myFile.WriteLine(sHeaders);
        // Export data.  
        for (int i = 0; i < dGV.RowCount; i++)
        {
             string stLine = "";
             for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
             {
                 if (dGV.Columns[j].Visible)
                 {
                     stLine = stLine.ToString() + dGV.Rows[i].Cells[j].Value.ToString() + ", ";
                 }
             }
                        myFile.WriteLine(stLine);
        }
     }
  }

But problem is if the value in the datagridviewcell is Harikrishna,Daxini then it will not exported properly,because there is comma in the cell value, but I have a need of including comma in the value.And it should export properly.How can I do that ? I tried with enclosing that value by double quotes and single quotes but it does not work.

有帮助吗?

解决方案

Spaces between seperating commas and an opening double quote can cause issues with CSV. Replace code like "val1", "val2" in your csv file with "val1","val2". That should fix your issue.

其他提示

Values that contain a ',' need to be escaped by surrounding them with double quotes.

         for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
         {
             if (dGV.Columns[j].Visible)
             {
                  var value = dGV.Rows[i].Cells[j].Value.ToString();
                  var append = value.Contains(",")
                                 ? string.Format("\"{0}\"", value)
                                 : value;
                  stLine = string.Format("{0}{1},", stLine, append) ;
             }
         }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top