我的项目有问题,我在尝试读取csv文件中的数据,我想将此数据转换为数据表。
我该怎么做?
我的代码:
System.Data.Odbc.OdbcConnection conn;
DataTable insDataTable = new DataTable();
System.Data.Odbc.OdbcDataAdapter da;
string folder = files.FullName;
string file = System.IO.Path.GetFileName(fUpload.PostedFile.FileName);
conn = new System.Data.Odbc.OdbcConnection(@"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + folder + ";Extensions=asc,csv,tab,txt;Persist Security Info=False");
da = new System.Data.Odbc.OdbcDataAdapter("select * from [" + file + "]", conn);
da.Fill(insDataTable);
它会出现如下错误:
错误[42S02] [微软] [ODBC文本 驱动程序] Microsoft Jet数据库 引擎找不到对象 'test.csv'。确保对象 存在,你拼写它的名字和 路径名称正确。
我正在检查文件'test.csv',文件路径是否正确:(
答案 0 :(得分:0)
几条评论。
1)您可能会发现FileHelpers库对执行此类操作很有用。 http://www.filehelpers.com/quick_start.html
2)您可能会发现以下功能对于获取所需信息非常有用。
Private Function GetTextDataSource(ByVal Filename As String, ByVal bIsPreview As Boolean, ByVal bIsCommaSeperated As Boolean) As DataView
Dim sConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("/Folder/Path/") & ";"
If chkUploadFileColumnsFirstRow.Checked Then
sConnectionString &= "Extended Properties='text;HDR=Yes;FMT=" & IIf(bIsCommaSeperated, "CSVDelimited", "TabDelimited") & ";IMEX=1'"
Else
sConnectionString &= "Extended Properties='text;FMT=" & IIf(bIsCommaSeperated, "CSVDelimited", "TabDelimited") & ";IMEX=1'"
End If
Dim objConnection As New OleDbConnection(sConnectionString)
Dim dv As DataView
Try
dv = GetOleDbDataView("SELECT " & IIf(bIsPreview, "TOP 1 ", "") & " * FROM [" & Replace(Filename, ";", "") & "]", objConnection)
Catch ex As OleDbException
Logger.Error(ex.Message)
AddError("Error selecting data from uploaded file, please ensure your file matches the correct specification and try again.")
Return Nothing
End Try
Return dv
End Function
Private Function GetOleDbDataView(ByVal SelectCommand As String, ByVal objConn As OleDbConnection) As DataView
' Create new OleDbCommand to return data from worksheet.
Dim objCmdSelect As New OleDbCommand(SelectCommand, objConn)
' Create new OleDbDataAdapter that is used to build a DataSet
' based on the preceding SQL SELECT statement.
Dim objAdapter1 As New OleDbDataAdapter()
' Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect
' Create new DataSet to hold information from the worksheet.
Dim objDataset1 As New DataSet()
' Fill the DataSet witht he information from the worksheet.
objAdapter1.Fill(objDataset1, "ExcelReturnData")
Return objDataset1.Tables(0).DefaultView
End Function