C# 在 .NET 中读取 CSV 文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1405038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Reading a CSV file in .NET?
提问by Janmejay
How do I read a CSV file using C#?
如何使用 C# 读取 CSV 文件?
回答by Marcin Deptu?a
You might be interested in Linq2Csv library at CodeProject. One thing you would need to check is that if it's reading the data when it needs only, so you won't need a lot of memory when working with bigger files.
您可能对CodeProject中的 Linq2Csv 库感兴趣。您需要检查的一件事是,它是否只在需要时读取数据,因此在处理更大的文件时不需要大量内存。
As for displaying the data on the browser, you could do many things to accomplish it, if you would be more specific on what are your requirements, answer could be more specific, but things you could do:
1. Use HttpListener class to write simple web server (you can find many samples on net to host mini-http server).
2. Use Asp.Net or Asp.Net Mvc, create a page, host it using IIS.
至于在浏览器上显示数据,你可以做很多事情来完成它,如果你更具体地了解你的要求,答案可以更具体,但你可以做的事情:
1.使用HttpListener类编写简单web 服务器(您可以在网上找到许多示例来托管 mini-http 服务器)。
2. 使用 Asp.Net 或 Asp.Net Mvc,创建一个页面,使用 IIS 托管它。
回答by John Hoven
I just used this library in my application. http://www.codeproject.com/KB/database/CsvReader.aspx. Everything went smoothly using this library, so I'm recommending it. It is free under the MIT License, so just include the notice with your source files.
我刚刚在我的应用程序中使用了这个库。 http://www.codeproject.com/KB/database/CsvReader.aspx。使用这个库一切都很顺利,所以我推荐它。它在 MIT 许可下是免费的,因此只需在您的源文件中包含通知即可。
I didn't display the CSV in a browser, but the author has some samples for Repeaters or DataGrids. I did run one of his test projects to test a Sort operation I have added and it looked pretty good.
我没有在浏览器中显示 CSV,但作者有一些 Repeaters 或 DataGrids 的示例。我确实运行了他的一个测试项目来测试我添加的排序操作,它看起来很不错。
回答by Freddy
This is just for parsing the CSV. For displaying it in a web page, it is simply a matter of taking the list and rendering it however you want.
这仅用于解析 CSV。为了在网页中显示它,只需获取列表并根据需要呈现它。
Note:This code example does not handle the situation where the input string line
contains newlines.
注意:此代码示例不处理输入字符串line
包含换行符的情况。
public List<string> SplitCSV(string line)
{
if (string.IsNullOrEmpty(line))
throw new ArgumentException();
List<string> result = new List<string>();
int index = 0;
int start = 0;
bool inQuote = false;
StringBuilder val = new StringBuilder();
// parse line
foreach (char c in line)
{
switch (c)
{
case '"':
inQuote = !inQuote;
break;
case ',':
if (!inQuote)
{
result.Add(line.Substring(start, index - start)
.Replace("\"",""));
start = index + 1;
}
break;
}
index++;
}
if (start < index)
{
result.Add(line.Substring(start, index - start).Replace("\"",""));
}
return result;
}
}
回答by alex
Seems like there are quite a few projects on CodeProject or CodePlex for CSV Parsing. Here is another CSV Parser on CodePlex
似乎在 CodeProject 或 CodePlex 上有很多用于 CSV 解析的项目。这是 CodePlex 上的另一个 CSV 解析器
http://commonlibrarynet.codeplex.com/
http://commonlibrarynet.codeplex.com/
This library has components for CSV parsing, INI file parsing, Command-Line parsing as well. It's working well for me so far. Only thing is it doesn't have a CSV Writer.
该库具有用于 CSV 解析、INI 文件解析、命令行解析的组件。到目前为止,它对我来说效果很好。唯一的问题是它没有 CSV Writer。
回答by Josh Close
You could try CsvHelper, which is a project I work on. Its goal is to make reading and writing CSV files as easy as possible, while being very fast.
你可以试试CsvHelper,这是我正在做的一个项目。它的目标是使读取和写入 CSV 文件尽可能简单,同时速度非常快。
Here are a few ways you can read from a CSV file.
您可以通过以下几种方法读取 CSV 文件。
// By type
var records = csv.GetRecords<MyClass>();
var records = csv.GetRecords( typeof( MyClass ) );
// Dynamic
var records = csv.GetRecords<dynamic>();
// Using anonymous type for the class definition
var anonymousTypeDefinition =
{
Id = default( int ),
Name = string.Empty,
MyClass = new MyClass()
};
var records = csv.GetRecords( anonymousTypeDefinition );
回答by wahrheit
A choice, without using third-party components, is to use the class Microsoft.VisualBasic.FileIO.TextFieldParser
(http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx) . It provides all the functions for parsing CSV. It is sufficient to import the Microsoft.VisualBasic assembly.
一个不使用第三方组件的选择是使用类Microsoft.VisualBasic.FileIO.TextFieldParser
( http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx)。它提供了解析 CSV 的所有功能。导入 Microsoft.VisualBasic 程序集就足够了。
var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(file);
parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
parser.SetDelimiters(new string[] { ";" });
while (!parser.EndOfData)
{
string[] row = parser.ReadFields();
/* do something */
}
回答by kombsh
You can use the Microsoft.VisualBasic.FileIO.TextFieldParserclass in C#:
您可以在 C# 中使用Microsoft.VisualBasic.FileIO.TextFieldParser类:
using System;
using System.Data;
using Microsoft.VisualBasic.FileIO;
static void Main()
{
string csv_file_path = @"C:\Users\Administrator\Desktop\test.csv";
DataTable csvData = GetDataTableFromCSVFile(csv_file_path);
Console.WriteLine("Rows count:" + csvData.Rows.Count);
Console.ReadLine();
}
private static DataTable GetDataTableFromCSVFile(string csv_file_path)
{
DataTable csvData = new DataTable();
try
{
using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
csvData.Rows.Add(fieldData);
}
}
}
catch (Exception ex)
{
}
return csvData;
}
回答by Dmitry Voytsekhovskiy
I recommend Angara.Table
, about save/load: http://predictionmachines.github.io/Angara.Table/saveload.html.
我推荐Angara.Table
关于保存/加载:http: //predictionmachines.github.io/Angara.Table/saveload.html。
It makes column types inference, can save CSV files and is much faster than TextFieldParser. It follows RFC4180 for CSV format and supports multiline strings, NaNs, and escaped strings containing the delimiter character.
它进行列类型推断,可以保存 CSV 文件,并且比 TextFieldParser 快得多。它遵循 CSV 格式的 RFC4180,并支持多行字符串、NaN 和包含分隔符的转义字符串。
The library is under MIT license. Source code is https://github.com/Microsoft/Angara.Table.
该库在 MIT 许可下。源代码是https://github.com/Microsoft/Angara.Table。
Though its API is focused on F#, it can be used in any .NET language but not so succinct as in F#.
虽然它的 API 专注于 F#,但它可以在任何 .NET 语言中使用,但不像在 F# 中那么简洁。
Example:
例子:
using Angara.Data;
using System.Collections.Immutable;
...
var table = Table.Load("data.csv");
// Print schema:
foreach(Column c in table)
{
string colType;
if (c.Rows.IsRealColumn) colType = "double";
else if (c.Rows.IsStringColumn) colType = "string";
else if (c.Rows.IsDateColumn) colType = "date";
else if (c.Rows.IsIntColumn) colType = "int";
else colType = "bool";
Console.WriteLine("{0} of type {1}", c.Name, colType);
}
// Get column data:
ImmutableArray<double> a = table["a"].Rows.AsReal;
ImmutableArray<string> b = table["b"].Rows.AsString;
Table.Save(table, "data2.csv");
回答by Travis Parks
I have been maintaining an open source project called FlatFilesfor several years now. It's available for .NET Core and .NET 4.5.1.
几年来,我一直在维护一个名为FlatFiles 的开源项目。它可用于 .NET Core 和 .NET 4.5.1。
Unlike most of the alternatives, it allows you to define a schema (similar to the way EF code-first works) with an extreme level of precision, so you aren't fight conversion issues all the time. You can map directly to your data classes, and there is also support for interfacing with older ADO.NET classes.
与大多数替代方案不同,它允许您以极高的精度定义模式(类似于 EF 代码优先的工作方式),因此您不会一直与转换问题作斗争。您可以直接映射到您的数据类,并且还支持与旧的 ADO.NET 类交互。
Performance-wise, it's been tuned to be one of the fastest parsers for .NET, with a plethora of options for quirky format differences. There's also support for fixed-length files, if you need it.
在性能方面,它已被调整为最快的 .NET 解析器之一,并为古怪的格式差异提供了大量选项。如果需要,还支持固定长度的文件。
回答by RajN
You can try Cinchoo ETL- an open source lib for reading and writing CSV files.
您可以尝试Cinchoo ETL- 一个用于读写 CSV 文件的开源库。
Couple of ways you can read CSV files
读取 CSV 文件的几种方法
Id, Name
1, Tom
2, Mark
This is how you can use this library to read it
这是您如何使用此库来阅读它
using (var reader = new ChoCSVReader("emp.csv").WithFirstLineHeader())
{
foreach (dynamic item in reader)
{
Console.WriteLine(item.Id);
Console.WriteLine(item.Name);
}
}
If you have POCO object defined to match up with CSV file like below
如果您定义了 POCO 对象以与如下所示的 CSV 文件匹配
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
}
You can parse the same file using this POCO class as below
您可以使用此 POCO 类解析相同的文件,如下所示
using (var reader = new ChoCSVReader<Employee>("emp.csv").WithFirstLineHeader())
{
foreach (var item in reader)
{
Console.WriteLine(item.Id);
Console.WriteLine(item.Name);
}
}
Please check out articles at CodeProjecton how to use it.
请查看CodeProject 中有关如何使用它的文章。
Disclaimer: I'm the author of this library
免责声明:我是这个库的作者