CSV C#中的文本限定符 [英] Text qualifier in CSV C#

查看:344
本文介绍了CSV C#中的文本限定符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static string ExportToCSV(DataTable dt, string path, string Filename)
       {


           try
           {
               string OutputMsg = "";
               if (string.IsNullOrEmpty(path))
               {
                   OutputMsg = "Path not defined";
                   return OutputMsg;
               }
               else
               {
                   //check the existence of path, if do not exist then create it
                   if (!Directory.Exists(path))
                   {
                       Directory.CreateDirectory(path);
                   }
              }

               if (string.IsNullOrEmpty(Filename))
               {
                   OutputMsg = "Filename is Mandatory";
                   return OutputMsg;
               }
               else
               {
                  using (var CTextWriter = new StreamWriter(path + "/" + Filename))
                   using (var csv = new CsvWriter(CTextWriter))
                   {
                       //seperater
                       csv.Configuration.Delimiter = "^";
                       csv.Configuration.QuoteAllFields = true;
                       if (dt != null)
                       {

                           foreach (DataColumn column in dt.Columns)
                           {
                               csv.WriteField(column.ColumnName, false);


                           }
                           csv.NextRecord();



In this way I am exporting my file to CSV. After generation my result looks like following:

877^False^CS-3a^^^55692^LProducts^PS3N7g1


But now if there will be \n charater in my last column value (PS\n 3N7\n g1)

则将其视为不同的记录.这是我的问题,我想为此使用文本限定符",它将所有值转换为反逗号,并将其作为单个记录.

我尝试过的事情:

我进行了很多搜索,但没有找到任何结果.

then it is considering as different record. which is my problem, I want to use "Text qualifier" for this which will get all the values into inverted commas and make it as single record.

What I have tried:

I have searched much but could not find any result for this.

推荐答案

我们不知道您使用什么来生成CSV数据,但是如果使用"^"作为列分隔符,那么您的数据应如下所示:
We don''t know what you are using to generate your CSV data, but if you are using ''^'' as a column separator, then you data should look like this:
1001^"A text string"^"666"^"After a number as a string"^^"After a blank column
1002^"Another text string"^"777"^"After a number as a string"^^"After a blank column
1003^"A double quote "" in a string"^"888"^"After a number as a string"^^"After a blank column

其中文本修饰符为""
因此,请检查您的数据并查看其确切外观.

Where the Text Qualifier is ''"''
So check your data and see exactly what it looks like.


这篇关于CSV C#中的文本限定符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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