2011-02-17 92 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