非常简单的 C# CSV 阅读器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1375410/
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
Very simple C# CSV reader
提问by DNN
I'd like to create an array from a CSV file.
我想从 CSV 文件创建一个数组。
This is about as simple as you can imagine, the CSV file will only ever have one line and these values:
这就像您想象的一样简单,CSV 文件将只有一行和这些值:
Device, SignalStrength, Location, Time, Age.
I'd like to put these values into one dimensional array.
我想将这些值放入一维数组中。
I've tried some examples but they've all been more complicated than required.
我试过一些例子,但它们都比要求的更复杂。
采纳答案by Andrew Hare
If there is only ever one line then do something like this:
如果只有一行,则执行以下操作:
using System;
using System.IO;
class Program
{
static void Main()
{
String[] values = File.ReadAllText(@"d:\test.csv").Split(',');
}
}
回答by Ramesh
You can try the some thing like the below LINQ snippet.
您可以尝试类似下面的 LINQ 代码段。
string[] allLines = File.ReadAllLines(@"E:\Temp\data.csv");
var query = from line in allLines
let data = line.Split(',')
select new
{
Device = data[0],
SignalStrength = data[1],
Location = data[2],
Time = data[3],
Age = Convert.ToInt16(data[4])
};
UPDATE:Over a period of time, things evolved. As of now, I would prefer to use this library http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx
更新:在一段时间内,事情发生了变化。截至目前,我更愿意使用这个库http://www.aspnetperformance.com/post/LINQ-to-CSV-library.aspx
回答by Chris Wilson
Here's a simple function I made. It accepts a string CSV line and returns an array of fields:
这是我制作的一个简单函数。它接受一个字符串 CSV 行并返回一个字段数组:
It works well with Excel generated CSV files, and many other variations.
它适用于 Excel 生成的 CSV 文件和许多其他变体。
public static string[] ParseCsvRow(string r)
{
string[] c;
string t;
List<string> resp = new List<string>();
bool cont = false;
string cs = "";
c = r.Split(new char[] { ',' }, StringSplitOptions.None);
foreach (string y in c)
{
string x = y;
if (cont)
{
// End of field
if (x.EndsWith("\""))
{
cs += "," + x.Substring(0, x.Length - 1);
resp.Add(cs);
cs = "";
cont = false;
continue;
}
else
{
// Field still not ended
cs += "," + x;
continue;
}
}
// Fully encapsulated with no comma within
if (x.StartsWith("\"") && x.EndsWith("\""))
{
if ((x.EndsWith("\"\"") && !x.EndsWith("\"\"\"")) && x != "\"\"")
{
cont = true;
cs = x;
continue;
}
resp.Add(x.Substring(1, x.Length - 2));
continue;
}
// Start of encapsulation but comma has split it into at least next field
if (x.StartsWith("\"") && !x.EndsWith("\""))
{
cont = true;
cs += x.Substring(1);
continue;
}
// Non encapsulated complete field
resp.Add(x);
}
return resp.ToArray();
}
回答by Zamir
This is what I used in a project, parses a single line of data.
这是我在一个项目中使用的,解析单行数据。
private string[] csvParser(string csv, char separator = ',')
{
List <string> = new <string>();
string[] temp = csv.Split(separator);
int counter = 0;
string data = string.Empty;
while (counter < temp.Length)
{
data = temp[counter].Trim();
if (data.Trim().StartsWith("\""))
{
bool isLast = false;
while (!isLast && counter < temp.Length)
{
data += separator.ToString() + temp[counter + 1];
counter++;
isLast = (temp[counter].Trim().EndsWith("\""));
}
}
parsed.Add(data);
counter++;
}
return parsed.ToArray();
}
http://zamirsblog.blogspot.com/2013/09/c-csv-parser-csvparser.html
http://zamirsblog.blogspot.com/2013/09/c-csv-parser-csvparser.html
回答by A. Richard Temps
My solution handles quotes, overriding field and string separators, etc. It is short and sweet.
我的解决方案处理引号、覆盖字段和字符串分隔符等。它简短而甜蜜。
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')
{
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
return retAry.ToArray();
}
回答by Paolo D.a
This fixed version of code above remember the last element of CVS row ;-)
上面这个固定版本的代码记住了 CVS 行的最后一个元素;-)
(tested with a CSV file with 5400 rows and 26 elements by row)
(使用 5400 行和 26 个逐行元素的 CSV 文件进行测试)
public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"') {
bool bolQuote = false;
StringBuilder bld = new StringBuilder();
List<string> retAry = new List<string>();
foreach (char c in r.ToCharArray())
if ((c == fieldSep && !bolQuote))
{
retAry.Add(bld.ToString());
bld.Clear();
}
else
if (c == stringSep)
bolQuote = !bolQuote;
else
bld.Append(c);
/* to solve the last element problem */
retAry.Add(bld.ToString()); /* added this line */
return retAry.ToArray();
}
回答by Andrew
First of all need to understand what is CSV and how to write it.
首先需要了解什么是CSV以及如何编写它。
(Most of answers (all of them at the moment) do not use this requirements, that's why they all is wrong!)
(大多数答案(目前所有答案)都没有使用此要求,这就是为什么它们都是错误的!)
- Every next string (
/r/n
) is next "table" row. - "Table" cells is separated by some delimiter symbol.
- As delimiter can be used ANY symbol. Often this is
\t
or,
. - Each cell possibly can contain this delimiter symbol inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)
- Each cell possibly can contains
/r/n
symbols inside of the cell (cell must to start with double quotes symbol and to have double quote in the end in this case)
- 每个下一个字符串 (
/r/n
) 都是下一个“表格”行。 - “表格”单元格由一些分隔符分隔。
- 可以使用任何符号作为分隔符。通常这是
\t
或,
。 - 每个单元格都可能在单元格内包含此分隔符(在这种情况下,单元格必须以双引号开头,并以双引号结尾)
- 每个单元格都可能包含
/r/n
单元格内部的符号(在这种情况下,单元 格必须以双引号符号开头并以双引号结尾)
Some time ago I had wrote simple class for CSV read/write based on standard Microsoft.VisualBasic.FileIO
library. Using this simple class you will be able to work with CSV like with 2 dimensions array.
前段时间我写了一个简单的类,用于基于标准Microsoft.VisualBasic.FileIO
库的CSV 读/写。使用这个简单的类,您将能够像使用二维数组一样使用 CSV。
Simple example of using my library:
使用我的库的简单示例:
Csv csv = new Csv("\t");//delimiter symbol
csv.FileOpen("c:\file1.csv");
var row1Cell6Value = csv.Rows[0][5];
csv.AddRow("asdf","asdffffff","5")
csv.FileSave("c:\file2.csv");
You can find my class by the following link and investigate how it's written: https://github.com/ukushu/DataExporter
您可以通过以下链接找到我的课程并调查它是如何编写的:https: //github.com/ukushu/DataExporter
This library code is really fast in work and source code is really short.
这个库代码运行速度非常快,源代码非常短。
PS: In the same time this solution will not work for unity.
PS:同时,此解决方案不适用于统一。
PS2: Another solution is to work with library "LINQ-to-CSV". It must also work well. But it's will be bigger.
PS2:另一个解决方案是使用库“LINQ-to-CSV”。它也必须运作良好。但它会更大。