有没有办法将csv文件读入矩阵,所以文件中的每个方格都是矩阵中的一个单元格?
答案 0 :(得分:3)
有许多开源CSV阅读器,您也可以轻松编写自己的代码。
首先来看看codeplex.com: http://kbcsv.codeplex.com/
或Codeproject教程: http://www.codeproject.com/KB/database/CsvReader.aspx
为了完成,这是我自己的实用程序类,用于从CSV文件中读取一行:
/// <summary>
/// Defines CSV reader states
/// </summary>
enum State
{
Initial,
Quote,
Data,
NestedQuote
}
/// <summary>
/// Initializes a new instance of the <see cref="CsvReader"/> class.
/// </summary>
/// <param name="inputStream">The input stream.</param>
public CsvReader(Stream inputStream)
{
if (inputStream == null)
throw new ArgumentNullException("inputStream");
reader = new StreamReader(inputStream);
}
/// <summary>
/// Reads a single line of CSV data.
/// </summary>
/// <returns>Array of CSV fields</returns>
public string[] Read()
{
var line = reader.ReadLine();
var retval = new List<string>();
if (line == null)
return null;
var state = State.Initial;
var text = new StringBuilder();
foreach (var ch in line)
switch (state)
{
case State.Initial:
if (ch == '"')
state = State.Quote;
else if (ch == ',')
retval.Add(string.Empty);
else
{
text.Append(ch);
state = State.Data;
}
break;
case State.Data:
if (ch == ',')
{
retval.Add(text.ToString());
text.Length = 0;
state = State.Initial;
}
else
text.Append(ch);
break;
case State.Quote:
if (ch == '"')
state = State.NestedQuote;
else
text.Append(ch);
break;
case State.NestedQuote:
if (ch == '"')
{
text.Append('"');
state = State.Quote;
break;
}
state = State.Data;
goto case State.Data;
}
retval.Add(text.ToString());
return retval.ToArray();
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
public void Dispose()
{
reader.Dispose();
}
制作矩阵(未经测试):
var data = new List<string[]>();
string[] line;
using(reader = new CsvReader(stream))
while((line = reader.Read()) != null)
data.Add(line);
result = data.Select(row => row.Select(cell => int.Parse(cell)).ToArray()).ToArray();
答案 1 :(得分:2)
VisualBasic命名空间中有一个文本阅读器,可以在C#中使用,并且可以很好地处理可怕的CSV文件:
只需在项目中添加对Microsoft.VisualBasic
的引用。
答案 2 :(得分:1)
使用正则表达式解析CSV:http://www.hotblue.com/article0000.aspx?a=0006
要使用自定义分隔符展开概念,请参阅此帖子:How do I write a regex to match a string that doesn't contain a word?
答案 3 :(得分:0)
有很多方法。从逐字节读取器开始。这取决于你的csv文件格式(有/没有标题,行结尾,或')。我写了自己的类。
一个好的读者: