CSV列中的新行导致问题

问题描述 投票:0回答:2

我有一个大的csv文件,其中有数百万行。样本csv行是

CODE,COMPANY NAME, DATE, ACTION
A,My Name , LLC,2018-01-28,BUY
B,Your Name , LLC,2018-01-25,SELL
C,
All Name , LLC,2018-01-21,SELL
D,World Name , LLC,2018-01-20,BUY

行C有新行,但实际上这是相同的记录。我想从cell \ field \ column中的csv行中删除换行符。

我厌倦了\r\nEnvirnment.NewLine和许多其他的东西,但无法使它工作。

这是我的代码..

 private DataTable CSToDataTable(string csvfile)
    {
        Int64 row = 0;
        try
        {

            string CSVFilePathName = csvfile; //@"C:\test.csv";
            string[] Lines = File.ReadAllLines(CSVFilePathName.Replace(Environment.NewLine, ""));
            string[] Fields;
            Fields = Lines[0].Split(new char[] { ',' });
            int Cols = Fields.GetLength(0);
            DataTable dt = new DataTable();
            //1st row must be column names; force lower case to ensure matching later on.
            for (int i = 0; i < Cols; i++)
                dt.Columns.Add(Fields[i].ToLower(), typeof(string));
            DataRow Row;
            for (row = 1; row < Lines.GetLength(0); row++)
            {
                Fields = Lines[row].Split(new char[] { ',' });
                Row = dt.NewRow();
                //Console.WriteLine(row);
                for (int f = 0; f < Cols; f++)
                {
                    Row[f] = Fields[f];
                }
                dt.Rows.Add(Row);
                if (row == 190063)
                {
                }
            }
            return dt;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

如何删除换行符并正确读取行?我不想根据业务需求跳过这些行。

c# csv c#-4.0
2个回答
2
投票

您的CSV文件格式不正确。为了成功解析和加载它们,您将不得不对它们进行清理。几个问题

  1. COMPANY NAME列包含字段分隔符。用引号括起来修复它们。
  2. CSV值中的新行 - 可以通过将相邻行组合为一个来修复此问题。

使用Cinchoo ETL,您可以清理并加载大文件,如下所示

string csv = @"CODE,COMPANY NAME, DATE, ACTION
A,My Name , LLC,2018-01-28,BUY
B,Your Name , LLC,2018-01-25,SELL
C,
All Name , LLC,2018-01-21,SELL
D,World Name , LLC,2018-01-20,BUY";

string bufferLine = null;
var reader = ChoCSVReader.LoadText(csv)
    .WithFirstLineHeader()
    .Setup(s => s.BeforeRecordLoad += (o, e) =>
    {
        string line = (string)e.Source;
        string[] tokens = line.Split(",");

        if (tokens.Length == 5)
        {
            //Fix the second and third value with quotes
            e.Source = @"{0},""{1},{2}"",{3}, {4}".FormatString(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4]);
        }
        else
        {
            //Fix the breaking lines, assume that some csv lines broken into max 2 lines
            if (bufferLine == null)
            {
                bufferLine = line;
                e.Skip = true;
            }
            else
            {
                line = bufferLine + line;
                tokens = line.Split(",");
                e.Source = @"{0},""{1},{2}"",{3}, {4}".FormatString(tokens[0], tokens[1], tokens[2], tokens[3], tokens[4]);
                line = null;
            }
        }
    });

foreach (var rec in reader)
    Console.WriteLine(rec.Dump());

//Careful to load millions rows into DataTable
//var dt = reader.AsDataTable();

希望能帮助到你。


1
投票

您尚未明确说明不需要的新行可能出现在文件中的标准是什么。因此,假设CSV文件中的“正确”行不以逗号结尾,并且如果以逗号结尾表示它不是格式正确的行,则可以执行以下操作:

static void Main(string[] args)
{
    string path = @"CSVFile.csv";

    List<CSVData> data = new List<CSVData>();
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        using (StreamReader sr = new StreamReader(fs))
        {
            sr.ReadLine();  // Header
            while (!sr.EndOfStream)
            {
                var line = sr.ReadLine();
                while (line.EndsWith(","))
                {
                    line += sr.ReadLine();
                }
                var items = line.Split(new string[] { "," }, StringSplitOptions.None);
                data.Add(new CSVData() { CODE = items[0], NAME = items[1], COMPANY = items[2], DATE = items[3], ACTION = items[4] });
            }
        }
    }

    Console.ReadLine();
}

public class CSVData
{
    public string CODE { get; set; }
    public string NAME { get; set; }
    public string COMPANY { get; set; }
    public string DATE { get; set; }
    public string ACTION { get; set; }
}

显然,这里要做很多错误处理(例如,在创建新的CSVData对象时确保你的items包含你想要的所有数据),但我认为这是你需要的开始。

© www.soinside.com 2019 - 2024. All rights reserved.