我们正在将Classic ASP站点转换为ASP.NET站点.其中一项功能是以CSV格式上传“模板”数据,以便导入数据库.那里有几种不同的记录类型(第一个字段总是标识数据的类型).
任务是将CSV转换为DataTable,以便验证它(新项目是要有更好的验证规则)
代码看起来非常简单 – 淡化(取出评论,Try / Catch等),如下所示:
Dim da As New System.Data.OleDb.OleDbDataAdapter Dim cn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strDirectory & ";" & "Extended Properties=""Text;HDR=No;FMT=Delimited;""") Dim cd As New System.Data.OleDb.OleDbCommand("SELECT * FROM " & strCSVFilename,cn) cn.Open() da.SelectCommand = cd da.Fill(dtData)
填充DataTable(dtData),但仅从CSV文件的第二行开始DESPITE“连接字符串”中存在“HDR = No”的事实.
我在这里想念的是什么?
解决方法
在文件的开头是否有可能导致第一行被跳过的东西?也许是一个不可打印的角色? NPC可能来自未以预期编码保存的文件.当我创建CSV文件时,我收到了您期望的结果.这是我用来测试的代码:
Private Sub Test() Dim TempDir = My.Computer.FileSystem.SpecialDirectories.Temp Dim TempFile = "Test.csv" '//Create our test file with a header row and three data rows Using FS As New System.IO.FileStream(System.IO.Path.Combine(TempDir,TempFile),IO.FileMode.Create,IO.FileAccess.Write,IO.FileShare.Read) Using SW As New System.IO.StreamWriter(FS,System.Text.Encoding.ASCII) SW.WriteLine("Col1,Col2") SW.WriteLine("R1","R1") SW.WriteLine("R2","R2") SW.WriteLine("R3","R3") End Using End Using '//Read the data into a table specifying that the first row should be treated as a header Using dtData As New DataTable() Using da As New System.Data.OleDb.OleDbDataAdapter Using cn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & TempDir & ";" & "Extended Properties=""Text;HDR=Yes;FMT=Delimited;""") Using cd As New System.Data.OleDb.OleDbCommand("SELECT * FROM " & TempFile,cn) cn.Open() da.SelectCommand = cd da.Fill(dtData) Trace.WriteLine("With header,expected 3,found " & dtData.Rows.Count) End Using End Using End Using End Using '//Read the data into a table again,this time specifying that the there isn't a header row Using dtData As New DataTable() Using da As New System.Data.OleDb.OleDbDataAdapter Using cn As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & TempDir & ";" & "Extended Properties=""Text;HDR=No;FMT=Delimited;""") Using cd As New System.Data.OleDb.OleDbCommand("SELECT * FROM " & TempFile,cn) cn.Open() da.SelectCommand = cd da.Fill(dtData) Trace.WriteLine("Without header,expected 4,found " & dtData.Rows.Count) End Using End Using End Using End Using '//Delete our temporary file System.IO.File.Delete(System.IO.Path.Combine(TempDir,TempFile)) End Sub
如果您将初始编码更改为Unicode,您将在结果中获得8行和9行,这可能就是您所看到的.如果结果是编码问题,可以将CharacterSet = Unicode添加到扩展属性中.