ASP.NET CSV & ODBC - System.Data.Odbc |
ASP.NET CSV & ODBC - System.Data.Odbc ใน ADO.NET ก็สามารถใช้ NameSpace ชื่อ System.Data.Odbc และ Driver={Microsoft Text Driver (*.txt; *.csv)}; เปิดไฟล์ CSV ผ่าน ODBC ได้เช่นเดียวกันครับ การใช้ ADO.NET ในการอ่าน จำเป็นจะต้องมีชื่อฟิวด์ระบุใน Column แรก
Language Code : VB.NET || C#
Framework : 1,2,3,4
csv/customer.csv
CustomerID,Name,Email,CountryCode,Budget,Used
"C001","Win Weerachai","[email protected]","TH","1,000,000.00","600,000.00"
"C002","John Smith","[email protected]","EN","2,000,000.00","800,000.00"
"C003","Jame Born","[email protected]","US","3,000,000.00","600,000.00"
"C004","Chalee Angel","[email protected]","US","4,000,000.00","100,000.00"
AspNetReadCSVDSNless.aspx
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.Odbc"%>
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim dt As DataTable
'*** Csv to DataTable ***'
dt = CsvCreateDataTable()
'*** BindData to Repeater ***'
myRepeater.DataSource = dt
myRepeater.DataBind()
End Sub
'*** DataTable ***'
Function CsvCreateDataTable() As DataTable
Dim objConn As New OdbcConnection
Dim dtAdapter As OdbcDataAdapter
Dim dt As New DataTable
Dim strConnString As String
strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};" & _
"Dbq=" & Server.MapPath("csv/") & ";Extensions=asc,csv,tab,txt;Persist Security Info=False"
objConn = New OdbcConnection(strConnString)
objConn.Open()
Dim strSQL As String
strSQL = "SELECT * FROM customer.csv"
dtAdapter = New OdbcDataAdapter(strSQL, objConn)
dtAdapter.Fill(dt)
dtAdapter = Nothing
objConn.Close()
objConn = Nothing
Return dt '*** Return DataTable ***'
End Function
</script>
<html>
<head>
<title>ThaiCreate.Com ASP.NET - CSV</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Repeater id="myRepeater" runat="server">
<HeaderTemplate>
<table border="1">
<tr>
<th>CustomerID</th>
<th>Name</th>
<th>Email</th>
<th>CountryCode</th>
<th>Budget</th>
<th>Used</th>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td align="center"><%#Container.DataItem(0) %></td> <!--or <Container.DataItem("CustomerID") -->
<td><%#Container.DataItem(1) %></td> <!--or <Container.DataItem("Name") -->
<td><%#Container.DataItem(2) %></td> <!--or <Container.DataItem("Email") -->
<td align="center"><%#Container.DataItem(3) %></td> <!--or <Container.DataItem("CountryCode") -->
<td align="right"><%#Container.DataItem(4) %></td> <!--or <Container.DataItem("Budget") -->
<td align="right"><%#Container.DataItem(5) %></td> <!--or <Container.DataItem("Used") -->
</tr>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Screenshot
|