将 CSV 导入数据表 [重复]
Posted
技术标签:
【中文标题】将 CSV 导入数据表 [重复]【英文标题】:Import CSV into a DataTable [duplicate] 【发布时间】:2011-06-29 10:18:09 【问题描述】:可能重复:How to read a csv file into a .net 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] [Microsoft][ODBC 文本 驱动程序] Microsoft Jet 数据库 引擎找不到对象 'test.csv'。确定对象 存在并且你拼写它的名字和 路径名正确。
我正在检查有一个文件'test.csv'并且文件路径是正确的:(
【问题讨论】:
已经在这里提问和回答了:***.com/questions/1050112/… 问题可能不同,但如何将 csv 读入数据表的答案保持不变。 这不是骗子,因为错误消息中的问题更多是关于基于 asp.net 上传创建 odbc 连接字符串而不是仅从 csv 创建数据表. 【参考方案1】:几个 cmets。
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
【讨论】:
以上是关于将 CSV 导入数据表 [重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何编写python程序将csv数据文件导入关系数据库而不插入重复条目
将 CSV 导入到 postgreSQL 中的表中,忽略重复项 - 亚马逊 AWS/RDS