问题描述
我工作的一个项目,我需要阅读的CSV文件,然后填充它的数据一个DataSet。我一直在寻找,我发现在OLEDB一些有趣的事情。
I'm working on a project and I need to read a CSV file and then fill a DataSet with its data. I've been searching and I have found some interesting things in OleDB.
我有一个类CSVReader:
I have a class CSVReader:
class CSVReader
{
public DataTable GetDataTable(string filePath)
{
OleDbConnection conn = new System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + Path.GetDirectoryName(filePath) + "; Extended Properties = \"Text;HDR=YES;FMT=Delimited\"");
conn.Open();
string strQuery = "SELECT * FROM [" + Path.GetFileName(filePath) + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, conn);
DataSet ds = new System.Data.DataSet("CSV File");
adapter.Fill(ds);
return ds.Tables[0];
}
}
和我把它从这里:
CSVReader datareader = new CSVReader();
DataTable dt = datareader.GetDataTable(filepath);
问题是,它解析第一行(标题行),如只是一个标识符列,我的意思是:这是CSV文件的标题:
The problem is that it parse the first line (the header line) like JUST ONE identifier for the column, I mean: This is the header of the CSV file:
Name, Product Name, Server, Vendor, Start Time, End Time, Host Name, User Name, Project Name, Usage time (hours)
和之后,也都用逗号分隔的数据。
And after it, there is all the data separated by commas.
当我阅读文件,填补了数据和打印的 dt.Columns.Count 的它表明,它只有1列。
When I read the file, fill the dataset and print dt.Columns.Count it shows that it only have 1 column.
任何帮助吗?
先谢谢了。
推荐答案
我一直用这个CSV库,通过C#读取CSV文件,它总是为我工作不错。
I always use this CSV library for reading CSV files in through C# its always worked good for me.
<一个href=\"http://www.$c$cproject.com/KB/database/CsvReader.aspx\">http://www.$c$cproject.com/KB/database/CsvReader.aspx
继承人的使用图书馆阅读CSF文件示例
Heres an example of reading a CSF file using the library
using System.IO;
using LumenWorks.Framework.IO.Csv;
void ReadCsv()
{
// open the file "data.csv" which is a CSV file with headers
using (CsvReader csv =
new CsvReader(new StreamReader("data.csv"), true))
{
int fieldCount = csv.FieldCount;
string[] headers = csv.GetFieldHeaders();
while (csv.ReadNextRecord())
{
for (int i = 0; i < fieldCount; i++)
Console.Write(string.Format("{0} = {1};",
headers[i], csv[i]));
Console.WriteLine();
}
}
}
这篇关于从创建CSV文件的DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!