生成CSV文件时转义逗号

时间:2019-07-11 13:31:53

标签: c# asp.net json csv

我正在使用c#将JSON文件转换为CSV,我能够正确执行。但我注意到有一列被分成两列,其余的列都移到了右边(因为JSON中的值之一带有逗号,并且在创建CSV文件时,代码出于某种考虑逗号也作为分隔符) 如何对现有代码进行必要的更改,以使其转义为逗号?

//used NewtonSoft json nuget package
            XmlNode xml = JsonConvert.DeserializeXmlNode("{items:{record:" + jsonContent + "}}");
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.LoadXml(xml.InnerXml);


            XmlReader xmlReader = new XmlNodeReader(xml);
            DataSet dataSet = new DataSet();
            dataSet.ReadXml(xmlReader);

            var dataTable = dataSet.Tables[0];

            //Datatable to CSV
            var lines = new List<string>();
            string[] columnNames = dataTable.Columns.Cast<DataColumn>().Select(column => column.ColumnName).ToArray();
            var header = string.Join(",", columnNames);
            lines.Add(header);
            var valueLines = dataTable.AsEnumerable().Select(row => string.Join(",", row.ItemArray));
            lines.AddRange(valueLines);
            File.WriteAllLines(@"PerfLog.csv", lines); 
//writing in to the file

0 个答案:

没有答案