gpt4 book ai didi

c# - 使用 C# 使用 OleDb 解析 CSV

转载 作者:IT王子 更新时间:2023-10-29 04:33:37 27 4
gpt4 key购买 nike

我知道这个话题已经死了,但我束手无策。

我需要解析一个 csv。这是一个非常普通的 CSV,解析逻辑是由另一位开发人员使用 OleDB 编写的,他发誓在他去度假之前它可以工作:)

CSV sample:
Dispatch Date,Master Tape,Master Time Code,Material ID,Channel,Title,Version,Duration,Language,Producer,Edit Date,Packaging,1 st TX,Last TX,Usage,S&P Rating,Comments,Replace,Event TX Date,Alternate Title
,a,b,c,d,e,f,g,h,,i,,j,k,,l,m,,n,

我遇到的问题是,根据我尝试的连接字符串,我会遇到各种错误。

当我尝试连接字符串时:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source="D:\TEST.csv\";Extended Properties="text;HDR=No;FMT=Delimited"

我得到错误:

'D:\TEST.csv' is not a valid path.  Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.

当我尝试连接字符串时:

Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\TEST.csv;Extended Properties=Excel 12.0;

或连接字符串

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\TEST.csv;Extended Properties=Excel 8.0;

我得到错误:

External table is not in the expected format.

我正在考虑丢弃所有代码并从头开始。有什么明显的我做错了吗?

最佳答案

您应该在连接字符串中仅指明目录名称。文件名将用于查询:

var filename = @"c:\work\test.csv";
var connString = string.Format(
@"Provider=Microsoft.Jet.OleDb.4.0; Data Source={0};Extended Properties=""Text;HDR=YES;FMT=Delimited""",
Path.GetDirectoryName(filename)
);
using (var conn = new OleDbConnection(connString))
{
conn.Open();
var query = "SELECT * FROM [" + Path.GetFileName(filename) + "]";
using (var adapter = new OleDbDataAdapter(query, conn))
{
var ds = new DataSet("CSV File");
adapter.Fill(ds);
}
}

您可以使用 decent CSV parser 而不是 OleDB (或 another one )。

关于c# - 使用 C# 使用 OleDb 解析 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6813607/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com