使用TextFieldParser解析字段中的逗号会导致额外的列

时间:2016-04-14 09:40:31

标签: c# csv datatable

关注上一个帖子Object reference on array with regex.replace()

function createTable() { tableContainer.appendChild(table); if ((table.nodeValue) != 0) { table.innerHTML = ""; } var row = document.createElement('tr'); table.appendChild(row); headcell = document.createElement('th'); row.appendChild(headcell); headcell.innerHTML = "Select"; headcell = document.createElement('th'); row.appendChild(headcell); headcell.innerHTML = "Sl.No"; Object.keys(obj[0]).forEach(function(val) { headcell = document.createElement('th'); row.appendChild(headcell); headcell.innerHTML = val; }); headcell = document.createElement('th'); row.appendChild(headcell); headcell.innerHTML = "Action"; } 中的列数很少,其中包含cpath等字段。不幸的是,

street,""test,format"", casio
由于csvReader.SetDelimiters(new string[] { "," }); 之间的逗号,

将空的额外列添加到DataTable csvData。因此,以下审讯:

是否存在从test and format删除逗号以便在"""test,format"""中获取street,""test format"", casio的技巧?

提前致谢

修改

csvData

1 个答案:

答案 0 :(得分:2)

TextFieldParser有一个属性HasFieldsEnclosedInQuotes,您应将其设置为true。然后逗号进入"测试,格式化"没有关系,因为它将被解释为单个值。

示例:

List<string[]> allLineFields = new List<string[]>();
string sampleLine = @"street,""test,format"", casio";
using (TextReader sr = new StringReader(sampleLine))
using (TextFieldParser parser = new TextFieldParser(sr))
{
    parser.HasFieldsEnclosedInQuotes = true;
    parser.Delimiters = new[] { "," };
    while (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields();
        allLineFields.Add(fields);
    }
}

结果是包含三个字段的单个string[]

    [0] {string[3]}     string[]
    [0] "street"        string
    [1] "test,format"   string
    [2] "casio"         string