当datatable包含逗号时,在csv中导出时出现问题 [英] Exporting in csv problematic when datatable contains comma

查看:162
本文介绍了当datatable包含逗号时,在csv中导出时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

专家,

我是Uday Satardekar.

我正在从数据库中获取记录并将其存储为CSV格式.

以下是我的CSV方法,正在将数据表传递给它.

Hi Expert,

I am Uday Satardekar.

I am fetching records from database and storing it into CSV Format.

Following is my CSV Method and I am passing datatable to it.

public void CreateCSVFile(DataTable dt, string strFilePath)
       {

           StreamWriter sw = new StreamWriter(strFilePath, false);

           int iColCount = dt.Columns.Count;
           for (int i = 0; i < iColCount; i++)
           {
               sw.Write(dt.Columns[i]);
               if (i < iColCount - 1)
               {
                   sw.Write(",");
               }
           }

           sw.Write(sw.NewLine);

           foreach (DataRow dr in dt.Rows)
           {
               for (int i = 0; i < iColCount; i++)
               {
                   if (!Convert.IsDBNull(dr[i]))
                   {
                       sw.Write(dr[i].ToString());
                   }

                   if (i < iColCount - 1)
                   {
                       sw.Write(",");
                   }
               }
               sw.Write(sw.NewLine);
           }
           sw.Close();
           MessageBox.Show("Exporting Completed");

       }

   }






以上对我来说很好.

但是,假设我的数据表结果中有逗号,则此函数也包含该逗号.

我的数据表中有公司,contact_person之类的字段,其中可能包含逗号.然后上面的功能也包含该逗号.

请帮助我如何跳过该逗号.

在此先感谢.......




And Above working fine for me.

But suppose if there is comma in any my datatable result then this function include that comma also.

In my datatable there are company,contact_person like field which may contains comma. Then above function include that comma also.

Please help me how to skip that comma.

Thanks in advance................

推荐答案

您可以将Microsoft.VisualBasic.FileIO命名空间的TextFieldParser类用作:

You can use TextFieldParser class of Microsoft.VisualBasic.FileIO namespace as:

using(var fileReader = New TextFieldParser("C:\ParserText.txt"))
{
   fileReader.TextFieldType = FieldType.Delimited;
   fileReader.SetDelimiters(",");
...
}


阅读 CSV格式 [ ^ ].

当CSV字段包含逗号,换行符或回车符等字符时,只需将整个字段数据嵌入双引号中即可.因此,在将每个字段添加到CSV数据字符串之前,只需检查这些字符并根据需要进行操作即可.

希望对您有帮助
Read upon CSV format[^].

When a CSV field contains characters such as commas or new lines or carriage returns, simple embed the entire field data within double quotes. Hence, prior adding each field to the CSV data string, simply check for these characters and do as necessary.

Hope this helps


这篇关于当datatable包含逗号时,在csv中导出时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆