有没有人知道一个允许你在C#中解析和读取.csv
文件的开源库?
答案 0 :(得分:26)
这里,您的真实编写使用泛型集合和迭代器块。它支持使用双重转义约定的双引号封闭文本字段(包括跨越多行的文本字段)(因此引用字段中的""
读作单引号字符)。它不支持:
但是如果你需要的话,所有这些都很容易添加。我没有在任何地方对它进行基准测试(我希望看到一些结果),但性能应该非常好 - 比任何基于.Split()
的任何东西都要好。
<强> Now on GitHub 强>
更新:感觉就像添加单引号封闭文本支持一样。这是一个简单的更改,但我在回复窗口中键入它,因此它未经测试。如果您更喜欢旧的(经过测试的)代码,请使用底部的修订链接。
public static class CSV
{
public static IEnumerable<IList<string>> FromFile(string fileName)
{
foreach (IList<string> item in FromFile(fileName, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromFile(string fileName, bool ignoreFirstLine)
{
using (StreamReader rdr = new StreamReader(fileName))
{
foreach(IList<string> item in FromReader(rdr, ignoreFirstLine)) yield return item;
}
}
public static IEnumerable<IList<string>> FromStream(Stream csv)
{
foreach (IList<string> item in FromStream(csv, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromStream(Stream csv, bool ignoreFirstLine)
{
using (var rdr = new StreamReader(csv))
{
foreach (IList<string> item in FromReader(rdr, ignoreFirstLine)) yield return item;
}
}
public static IEnumerable<IList<string>> FromReader(TextReader csv)
{
//Probably should have used TextReader instead of StreamReader
foreach (IList<string> item in FromReader(csv, ignoreFirstLineDefault)) yield return item;
}
public static IEnumerable<IList<string>> FromReader(TextReader csv, bool ignoreFirstLine)
{
if (ignoreFirstLine) csv.ReadLine();
IList<string> result = new List<string>();
StringBuilder curValue = new StringBuilder();
char c;
c = (char)csv.Read();
while (csv.Peek() != -1)
{
switch (c)
{
case ',': //empty field
result.Add("");
c = (char)csv.Read();
break;
case '"': //qualified text
case '\'':
char q = c;
c = (char)csv.Read();
bool inQuotes = true;
while (inQuotes && csv.Peek() != -1)
{
if (c == q)
{
c = (char)csv.Read();
if (c != q)
inQuotes = false;
}
if (inQuotes)
{
curValue.Append(c);
c = (char)csv.Read();
}
}
result.Add(curValue.ToString());
curValue = new StringBuilder();
if (c == ',') c = (char)csv.Read(); // either ',', newline, or endofstream
break;
case '\n': //end of the record
case '\r':
//potential bug here depending on what your line breaks look like
if (result.Count > 0) // don't return empty records
{
yield return result;
result = new List<string>();
}
c = (char)csv.Read();
break;
default: //normal unqualified text
while (c != ',' && c != '\r' && c != '\n' && csv.Peek() != -1)
{
curValue.Append(c);
c = (char)csv.Read();
}
result.Add(curValue.ToString());
curValue = new StringBuilder();
if (c == ',') c = (char)csv.Read(); //either ',', newline, or endofstream
break;
}
}
if (curValue.Length > 0) //potential bug: I don't want to skip on a empty column in the last record if a caller really expects it to be there
result.Add(curValue.ToString());
if (result.Count > 0)
yield return result;
}
private static bool ignoreFirstLineDefault = false;
}
答案 1 :(得分:23)
在CodeProject上查看A Fast CSV Reader。
答案 2 :(得分:21)
last time this question was asked,这是the answer我给的:
如果您只是尝试使用C#读取CSV文件,最简单的方法是使用Microsoft.VisualBasic.FileIO.TextFieldParser类。它实际上内置于.NET Framework中,而不是第三方扩展。
是的,它位于Microsoft.VisualBasic.dll
,但这并不意味着您无法使用C#(或任何其他CLR语言)。
以下是一个使用示例,取自MSDN documentation:
Using MyReader As New _
Microsoft.VisualBasic.FileIO.TextFieldParser("C:\testfile.txt")
MyReader.TextFieldType = FileIO.FieldType.Delimited
MyReader.SetDelimiters(",")
Dim currentRow As String()
While Not MyReader.EndOfData
Try
currentRow = MyReader.ReadFields()
Dim currentField As String
For Each currentField In currentRow
MsgBox(currentField)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & _
"is not valid and will be skipped.")
End Try
End While
End Using
同样,这个例子是在VB.NET中,但将它转换为C#是微不足道的。
答案 3 :(得分:8)
我非常喜欢FileHelpers库。它很快,它是C#100%,它可用于免费,它非常灵活且易于使用。
答案 4 :(得分:4)
我在C#中实现了Daniel Pryden的答案,因此更容易剪切和粘贴以及自定义。我认为这是解析CSV文件最简单的方法。只需添加引用即可完成。
将Microsoft.VisualBasic
参考添加到您的项目
然后这是来自Joel答案的C#中的示例代码:
using (Microsoft.VisualBasic.FileIO.TextFieldParser MyReader = new
Microsoft.VisualBasic.FileIO.TextFieldParser(filename))
{
MyReader.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited;
MyReader.SetDelimiters(",");
while (!MyReader.EndOfData)
{
try
{
string[] fields = MyReader.ReadFields();
if (first)
{
first = false;
continue;
}
// This is how I treat my data, you'll need to throw this out.
//"Type" "Post Date" "Description" "Amount"
LineItem li = new LineItem();
li.date = DateTime.Parse(fields[1]);
li.description = fields[2];
li.Value = Convert.ToDecimal(fields[3]);
lineitems1.Add(li);
}
catch (Microsoft.VisualBasic.FileIO.MalformedLineException ex)
{
MessageBox.Show("Line " + ex.Message +
" is not valid and will be skipped.");
}
}
}
答案 5 :(得分:3)
除了解析/读取之外,一些库还会做其他很好的事情,比如将解析后的数据转换为对象。
以下是使用CsvHelper(我维护的库)将CSV文件读入对象的示例。
var csv = new CsvHelper( File.OpenRead( "file.csv" ) );
var myCustomObjectList = csv.Reader.GetRecords<MyCustomObject>();
默认情况下,约定用于将标题/列与属性进行匹配。您可以通过更改设置来更改行为。
// Using attributes:
public class MyCustomObject
{
[CsvField( Name = "First Name" )]
public string StringProperty { get; set; }
[CsvField( Index = 0 )]
public int IntProperty { get; set; }
[CsvField( Ignore = true )]
public string ShouldIgnore { get; set; }
}
有时您不会“拥有”要填充数据的对象。在这种情况下,您可以使用流畅的类映射。
// Fluent class mapping:
public sealed class MyCustomObjectMap : CsvClassMap<MyCustomObject>
{
public MyCustomObjectMap()
{
Map( m => m.StringProperty ).Name( "First Name" );
Map( m => m.IntProperty ).Index( 0 );
Map( m => m.ShouldIgnore ).Ignore();
}
}
答案 6 :(得分:2)
您可以使用 Microsoft.VisualBasic.FileIO.TextFieldParser
从上面的文章
获取以下代码示例static void Main()
{
string csv_file_path=@"C:\Users\Administrator\Desktop\test.csv";
DataTable csvData = GetDataTabletFromCSVFile(csv_file_path);
Console.WriteLine("Rows count:" + csvData.Rows.Count);
Console.ReadLine();
}
private static DataTable GetDataTabletFromCSVFile(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;
}