下面是我的CSV结构(刚刚取了标题行和第一个数据行。
Header 1,Header 2,Header 3,Header 4,Header5
Value 1,"Value2 a,Value 2b","Value3 a,Value 3b",Value 4,Value5
假设CSV具有逗号分隔分隔符,我可以读取CSV、读取标题行和数据行。
几个代码片段-
var fileContent = File.ReadAllLines(csvFile.FullName);
List<string> headerValues = null;
List<string> contentAllRows= null;
if (fileContent !=null && fileContent.Any())
{
headerValues = fileContent.First().Split(separators).ToList();
headerValues.ForEach(h => h = h.Trim());
contentAllRows = fileContent.Skip(1).ToList();
}
for (int row = 0; row <= contentAllRows.Count - 1; row++)
{
var column = contentAllRows[row].Split(separators).ToList();
}
上述代码片段的输出
headerValues[0] = "Header 1"
headerValues[1] = "Header 2"
headerValues[2] = "Header 3"
headerValues[3] = "Header 4"
headerValues[4] = "Header5"
contentAllRows ="Value 1,\"Value2 a,Value 2b\",\"Value3 a,Value 3b\",Value 4,Value5"
columns[0] = "Value 1"
columns[1] = "\"Value2 a"
columns[2] = "Value 2b\""
columns[3] = "\"Value3 a"
columns[4] = "Value 3b\""
columns[5] = "Value 4"
columns[6] = "Value5"
我的预期输出(相对于上面的每个标头值)-
columns[0]="Value 1"
columns[1]="Value2 a,Value 2b"
columns[2]="Value3 a,Value 3b"
columns[3]=""
columns[4]="Value5"
在我看来,在上述情况下,Split()
就是问题所在。对于上面的场景,我们有一个简单的解决方案吗?我正在考虑在读取CSV的同时拥有强类型的对象。上面的场景适合CSV helper模块@ https://joshclose.github.io/CsvHelper/2.x/吗?有什么建议吗?
https://stackoverflow.com/questions/52024242
复制相似问题