我正在编写一个程序来读取CSV文件并验证数据。csv文件以逗号分隔。
csv文件包含在线检索的销售订单,因此我们无法实际编辑CSV文件本身。我需要读取文件并将其拆分到单元格中。但是,产品描述将包含更多的逗号,这会影响我访问数据的方式。
我提取这些值的代码如下所示。
private void csvParse()
{
List products = new List();
List quantities = new List();
List price = new List();
using (var reader = new StreamReader(txt_filePath.Text.ToString()))
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
products.Add(values[0]);
quantities.Add(values[2]);
values[3] = values[3].Substring(4);
price.Add(values[3]);
}
}
if (validateData(products, quantities, price) != "")
{
MessageBox.Show(validateData(products, quantities, price));
}
}
有没有什么办法可以忽略集合单元格中的列,或者可以用另一个分隔符来区分这些列?
下面是我的csv文件中的一行代码片段。
原始CSV数据如下:
TO12345,"E45 Dermatological Moisturising Lotion, 500 ml",765,GBP 1.75
发布于 2018-08-02 18:28:19
您可以从nuGet使用LinqToCSV。即:
void Main()
{
List sample = new List {
new MyData {Id=1, Name="Hammer", Description="Everything looks like a nail to a hammer, doesn't it?"},
new MyData {Id=2, Name="C#", Description="A computer language."},
new MyData {Id=3, Name="Go", Description="Yet another language, from Google, cross compiles natively."},
new MyData {Id=3, Name="BlahBlah"},
};
string fileName = @"c:\temp\MyCSV.csv";
File.WriteAllText(fileName,"Id,My Product Name,Ignore1,Ignore2,Description\n");
File.AppendAllLines(fileName, sample.Select(s => $@"{s.Id},""{s.Name}"",""ignore this"",""skip this too"",""{s.Description}"""));
CsvContext cc = new CsvContext();
CsvFileDescription inputFileDescription = new CsvFileDescription
{
SeparatorChar = ',',
FirstLineHasColumnNames = true,
IgnoreUnknownColumns=true
};
IEnumerable fromCSV = cc.Read(fileName, inputFileDescription);
foreach (var d in fromCSV)
{
Console.WriteLine($@"ID:{d.Id},Name:""{d.Name}"",Description:""{d.Description}""");
}
}
public class MyData
{
[CsvColumn(FieldIndex = 1, Name="Id", CanBeNull = false)]
public int Id { get; set; }
[CsvColumn(FieldIndex = 2, Name="My Product Name",CanBeNull = false, OutputFormat = "C")]
public string Name { get; set; }
[CsvColumn(FieldIndex = 5, Name="Description",CanBeNull = true, OutputFormat = "C")]
public string Description { get; set; }
}
发布于 2018-08-02 18:50:49
它应该可以工作..:)
var csvSplit = new Regex("(?:^|,)(\"(?:[^\"]+|\"\")*\"|[^,]*)", RegexOptions.Compiled);
string[] csvlines = File.ReadAllLines(txt_filePath.Text.ToString());
var query = csvlines.Select(csvline => new
{
data = csvSplit.Matches(csvline)
}).Select(t => t.data);
var row = query.Select(matchCollection =>
(from Match m in matchCollection select (m.Value.Contains(',')) ? m.Value.Replace(",", "") : m.Value)
.ToList()).ToList();
发布于 2021-02-25 19:29:13
您还可以使用Microsoft.VisualBasic.FileIO.TextFieldParser类。更详细的答案在这里:TextFieldParser
https://stackoverflow.com/questions/51650343
复制相似问题