阅读带有双引号的csv与lumenworks csv阅读器

时间:2014-10-15 11:10:03

标签: c# .net csv lumenworks

我正在使用Lumenworks csv阅读器阅读csv文件。以下是一个示例记录

"001-0000265-003"|"Some detail"|"detal1"|"detail2"|"detal3"|"detail4"|"detail5"|"detail6"

我已经使用下面的构造函数创建了一个类来读取此文件

using (var input = new CsvReader(stream, true, '|'))
{
//logic to create an xml here
}

当细节内没有双引号时,这样可以正常工作。但当像这样的scinarios

"001-0000265-003"|"Some " detail"|"detal1"|"detail2"|"detal3"|"detail4"|"detail5"|"detail6"

读者抛出异常

An unhandled exception of type 'LumenWorks.Framework.IO.Csv.MalformedCsvException' occurred in LumenWorks.Framework.IO.dll

然后我使用了带有7个参数的CsvReader构造函数,

CsvReader(stream, true, '|', '"', '"', '#', LumenWorks.Framework.IO.Csv.ValueTrimmingOptions.All))

但我仍然得到同样的错误。请提供任何建议。

我正在阅读一些复杂的文件如下,

"001-0000265-003"|"ABC 33"X23" CDE 32'X33" AAA, BB'C"|"detal1"|"detail2"|"detal3"|"detail4"|"detail5"|"detail6"

1 个答案:

答案 0 :(得分:6)

我已经使用您的示例数据对其进行了测试,并且很难修复此格式不正确的行(例如来自Catch - 块)。所以我不会使用引号字符,而只是使用管道分隔符,然后通过"删除csv[i].Trim('"')

这是一种解析文件并返回所有行的方法'字段:

private static List<List<string>> GetAllLineFields(string fullPath)
{
    List<List<string>> allLineFields = new List<List<string>>();
    var fileInfo = new System.IO.FileInfo(fullPath);

    using (var reader = new System.IO.StreamReader(fileInfo.FullName, Encoding.Default))
    {
        Char quotingCharacter = '\0'; // no quoting-character;
        Char escapeCharacter = quotingCharacter;
        Char delimiter = '|';
        using (var csv = new CsvReader(reader, true, delimiter, quotingCharacter, escapeCharacter, '\0', ValueTrimmingOptions.All))
        {
            csv.DefaultParseErrorAction = ParseErrorAction.ThrowException;
            //csv.ParseError += csv_ParseError;  // if you want to handle it somewhere else
            csv.SkipEmptyLines = true;

            while (csv.ReadNextRecord())
            {
                List<string> fields = new List<string>(csv.FieldCount);
                for (int i = 0; i < csv.FieldCount; i++)
                {
                    try
                    {
                        string field = csv[i];
                        fields.Add(field.Trim('"'));
                    } catch (MalformedCsvException ex)
                    {
                        // log, should not be possible anymore
                        throw;
                    }
                }
                allLineFields.Add(fields);
            }
        }
    }
    return allLineFields;
}

使用包含样本数据的文件进行测试和输出:

List<List<string>> allLineFields = GetAllLineFields(@"C:\Temp\Test\CsvFile.csv");
    foreach (List<string> lineFields in allLineFields)
        Console.WriteLine(string.Join(",", lineFields.Select(s => string.Format("[{0}]", s))));

[001-0000265-003],[Some detail],[detal1],[detail2],[detal3],[detail4],[detail5],[detail6]
[001-0000265-003],[Some " detail],[detal1],[detail2],[detal3],[detail4],[detail5],[detail6]