使用 C# 读取 CSV 文件
我正在编写一个简单的导入应用程序,需要读取 CSV 文件,在 DataGrid 中显示结果,并在另一个网格中显示 CSV 文件的损坏行。例如,显示另一个网格中短于 5 个值的线。我试图这样做:
StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
row = line.Split(',');
importingData.Add(new Transaction
{
Date = DateTime.Parse(row[0]),
Reference = row[1],
Description = row[2],
Amount = decimal.Parse(row[3]),
Category = (Category)Enum.Parse(typeof(Category), row[4])
});
}
但在这种情况下对数组进行操作非常困难。有没有更好的方法来分割值?
I'm writing a simple import application and need to read a CSV file, show result in a DataGrid
and show corrupted lines of the CSV file in another grid. For example, show the lines that are shorter than 5 values in another grid. I'm trying to do that like this:
StreamReader sr = new StreamReader(FilePath);
importingData = new Account();
string line;
string[] row = new string [5];
while ((line = sr.ReadLine()) != null)
{
row = line.Split(',');
importingData.Add(new Transaction
{
Date = DateTime.Parse(row[0]),
Reference = row[1],
Description = row[2],
Amount = decimal.Parse(row[3]),
Category = (Category)Enum.Parse(typeof(Category), row[4])
});
}
but it's very difficult to operate on arrays in this case. Is there a better way to split the values?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(12)
不要重新发明轮子。利用 .NET BCL 中已有的功能。
以下是示例代码:
它在我的 C# 项目中非常适合我。
以下是更多链接/信息:
Don't reinvent the wheel. Take advantage of what's already in .NET BCL.
Microsoft.VisualBasic
(yes, it says VisualBasic but it works in C# just as well - remember that at the end it is all just IL)Microsoft.VisualBasic.FileIO.TextFieldParser
class to parse CSV fileHere is the sample code:
It works great for me in my C# projects.
Here are some more links/informations:
我推荐 来自 NuGet 的 CsvHelper。
PS:关于其他更多赞成的答案,我很抱歉,但添加对 Microsoft.VisualBasic 的引用是:
I recommend CsvHelper from NuGet.
PS: Regarding other more upvoted answers, I'm sorry but adding a reference to
Microsoft.VisualBasic
is:我的经验是,有许多不同的 csv 格式。特别是它们如何处理字段内引号和分隔符的转义。
这些是我遇到的变体:
我已经尝试了许多现有的 csv 解析器,但没有一个可以处理我遇到的变体。从文档中找出解析器支持哪些转义变体。
在我的项目中,我现在使用 VB TextFieldParser 或自定义拆分器。
My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.
These are the variants I have ran into:
I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.
In my projects I now use either the VB TextFieldParser or a custom splitter.
有时,当您不想重新发明轮子时,使用库很酷,但在这种情况下,与使用库相比,可以用更少的代码行完成相同的工作,并且更易于阅读。
这是一种不同的方法,我发现它非常容易使用。
Sometimes using libraries are cool when you do not want to reinvent the wheel, but in this case one can do the same job with fewer lines of code and easier to read compared to using libraries.
Here is a different approach which I find very easy to use.
CSV 可能会很快变得复杂真正。
使用健壮且经过充分测试的东西:
文件助手:
www.filehelpers.net
CSV can get complicated real fast.
Use something robust and well-tested:
FileHelpers:
www.filehelpers.net
读取和写入 CSV 文件的开源库
此列表中的另一个是 Cinchoo ETL - 一个用于 下面的示例CSV文件
可以快速使用库加载它们,如下所示,
如果您的POCO类匹配CSV文件,
则可以使用它来加载CSV文件,如下所示,
请在CodeProject 了解如何使用它。
免责声明:我是这个库的作者
Another one to this list, Cinchoo ETL - an open source library to read and write CSV files
For a sample CSV file below
Quickly you can load them using library as below
If you have POCO class matching the CSV file
You can use it to load the CSV file as below
Please check out articles at CodeProject on how to use it.
Disclaimer: I'm the author of this library
我在这里使用它:
http://www.codeproject.com/KB/database/GenericParser .aspx
上次我在寻找类似的东西时,我发现它是对此的答案 问题。
I use this here:
http://www.codeproject.com/KB/database/GenericParser.aspx
Last time I was looking for something like this I found it as an answer to this question.
这是我今天编写的一个解决方案,用于解决我需要在不依赖外部库的情况下解析 CSV 的情况。我还没有测试大文件的性能,因为它与我的特定用例无关,但我希望它在大多数情况下都能表现得相当好。
Here's a solution I coded up today for a situation where I needed to parse a CSV without relying on external libraries. I haven't tested performance for large files since it wasn't relevant to my particular use case but I'd expect it to perform reasonably well for most situations.
首先需要了解什么是CSV以及如何编写它。
/r/n
)是下一个“表”行。\t
或,
/r/n
符号(在这种情况下,单元格必须以引号符号开头,并以该符号结尾)C#/Visual Basic 处理 CSV 文件的最简单方法是使用标准 <代码>Microsoft.VisualBasic 库。您只需将所需的引用和以下字符串添加到您的类中:
是的,您可以在 C# 中使用它,不用担心。该库可以读取相对较大的文件并支持所有所需的规则,因此您将能够使用所有 CSV 文件。
前段时间我基于这个库编写了用于 CSV 读/写的简单类。使用这个简单的类,您将能够像使用二维数组一样使用 CSV。
您可以通过以下链接找到我的课程:
https://github.com/ukushu/DataExporter
简单的使用示例:
First of all need to understand what is CSV and how to write it.
/r/n
) is next "table" row.\t
or,
/r/n
sybols (cell must to start with quotes symbol and ends with this symbol in this case)The easiest way for C#/Visual Basic to work with CSV files is to use standard
Microsoft.VisualBasic
library. You just need to add needed reference, and the following string to your class:Yes, you can use it in C#, don't worry. This library can read relatively big files and supports all of needed rules, so you will be able to work with all of CSV files.
Some time ago I had wrote simple class for CSV read/write based on this library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
You can find my class by the following link:
https://github.com/ukushu/DataExporter
Simple example of using:
要完成前面的答案,可能需要 CSV 文件中的对象集合,由
TextFieldParser
或string.Split
方法解析,然后将每一行转换为通过反射的对象。显然,您首先需要定义一个与 CSV 文件的行匹配的类。我使用了来自 Michael Kropat 的简单 CSV 序列化器:通用类到 CSV(所有属性)
并重用他的方法来获取所需类的字段和属性。
我使用以下方法反序列化我的 CSV 文件:
To complete the previous answers, one may need a collection of objects from his CSV File, either parsed by the
TextFieldParser
or thestring.Split
method, and then each line converted to an object via Reflection. You obviously first need to define a class that matches the lines of the CSV file.I used the simple CSV Serializer from Michael Kropat found here: Generic class to CSV (all properties)
and reused his methods to get the fields and properties of the wished class.
I deserialize my CSV file with the following method:
我强烈建议使用 CsvHelper。
这是一个简单的示例:
完整的文档可以在以下位置找到:https://joshclose.github.io/CsvHelper
I'd highly suggest using CsvHelper.
Here's a quick example:
Full documentation can be found at: https://joshclose.github.io/CsvHelper