如何在C#中通过OLEDB导入CSV文件时指定分隔符
我需要在Microsoft SQL Server 2000中执行复杂的导入。
由于在DTS中执行它太复杂了,我正在尝试使用一个小的C#程序,但是当我需要导入CSV文件时遇到问题:这个文件使用分号作为字段分隔符而不是逗号和我无法让.NET的OLE DB提供程序识别它。
我已经在网上找到了各种“解决方案”,例如in the connection string or using a
使用Extended Properties="Text; Format=Delimited"
或“Extended Properties =”Text; Format = Delimited(;)“ in the connection string or using a
schema.ini`文件无济于事。
这是我正在使用的实际代码:
DataTable Table = new DataTable(); using (OleDbConnection Connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text;HDR=Yes;Format=Delimited\"")) { Connection.Open(); using (OleDbCommand Command = Connection.CreateCommand()) { Command.CommandText = "select [Field 1], [Field 2] from [file.csv]"; using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command)) { Adapter.Fill(Table); } } } using (SqlConnection Connection = new SqlConnection("Data Source=server; Initial Catalog=database; User Id=user; Password=password;")) { Connection.Open(); using (SqlCommand Command = Connection.CreateCommand()) { Command.CommandText = "insert into [table] ([field_1], [field_2], ...) values (@field_1, @field_2, ...)"; Command.Parameters.Add("field_1", SqlDbType.Date, 0, "Field 1"); Command.Parameters.Add("field_2", SqlDbType.VarChar, 100, "Field 2"); ... using (SqlDataAdapter Adapter = new SqlDataAdapter()) { Adapter.InsertCommand = Command; Adapter.Update(Table); } } }
关于如何使用分号作为字段分隔符而不依赖外部libriaries的任何想法?
笔记:
- “不依赖于外部libriaries”位是因为我需要将文件直接导入到数据库中,并且我找不到的库可以执行此操作(它们返回字符串),并且我们的PHB不会为商业解决方案丢一分钱。
- 我知道我可以通过DTS导入文件,但我需要在导入之前和之后对工作流和文件更改执行复杂的分支,这将导致跳入和跳出DTS。
- 在DTS中做所有事情对我来说都不实用,因为我不熟悉ActiveX和VBScript编码。
提前谢谢,安德烈。
编辑1 – @andyb:测试schema.ini
方法的程序代码:
String ConnectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0; Data Source={0}; Extended Properties=\"Text\"", Environment.CurrentDirectory); DataTable Table = new DataTable(); using (OleDbConnection Connection = new OleDbConnection(ConnectionString)) { Connection.Open(); using (OleDbCommand Command = Connection.CreateCommand()) { Command.CommandText = "select * from [file.csv]"; using (OleDbDataAdapter Adapter = new OleDbDataAdapter(Command)) { Adapter.Fill(Table); } } }
评论者是对的,你的提供者语法是错误的。
但是,这不是问题。 遗憾的是,您无法在oledb连接字符串中指定自定义分隔符。 而是在与包含以下内容的源文件相同的目录中创建schema.ini文件:
[file.csv] Format=Delimited(;)
笨拙,但确实有效。
schema.ini文件必须以Unicode或ANSI保存,而不是以UTF-8保存。
您的数据文件也必须保存为Unicode而不是UTF-8。
你必须在schema.ini文件中写入你的csv文件名(而不是[file.csv],例如:test.csv将在第0行有一个带有[test.csv]文本的schema.ini:
[test.csv] Format=Delimited(;)