2011-02-17 91 views
0

可能重复:
How to read a csv file into a .net datatable导入CSV到一个DataTable

我在我的项目中,我想在一个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”和文件路径是正确的:(

+1

已经提出和回答的位置:http://stackoverflow.com/questions/1050112/how-to-read-a-csv-file-into-a-net-datatable的问题可能会有所不同,但如何将csv读入数据表的答案仍然相同。 – David 2011-02-17 21:36:32

回答

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