ASP.NET Read CSV files ตัวอย่างนี้จะเป็นการเปิดไฟล์ csv ใช้การอ่านแบบ Text Files ใช้เครื่องหมาย Comma (,) ในการแบ่ง Column จากนั้นแปลงให้อยู่ในรูปแบบของ DataTable
Language Code : VB.NET || C#
Framework : 1,2,3,4
customer.csv
C001,Win Weerachai,[email protected],TH,1000000,600000
C002,John Smith,[email protected],EN,2000000,800000
C003,Jame Born,[email protected],US,3000000,600000
C004,Chalee Angel,[email protected],US,4000000,100000
AspNetReadCSV.aspx
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.IO"%>
<%@ Page Language="VB" %>
<script runat="server">
Sub Page_Load(sender As Object, e As EventArgs)
Dim dt As DataTable
'*** DataTable ***'
dt = ReadCSV() '*** Convert CSV to DataTable ***'
'*** BindData to Repeater ***'
myRepeater.DataSource = dt
myRepeater.DataBind()
End Sub
'*** CSV & DataTable ***'
Function ReadCSV() As DataTable
Dim dt As New DataTable
Dim dr As DataRow
'*** Column ***'
dt.Columns.Add("CustomerID")
dt.Columns.Add("Name")
dt.Columns.Add("Email")
dt.Columns.Add("CountryCode")
dt.Columns.Add("Budget")
dt.Columns.Add("Used")
Dim StrWer As StreamReader
Dim strLine As String
StrWer = File.OpenText(Server.MapPath("csv/customer.csv"))
Do Until StrWer.EndOfStream
strLine = StrWer.ReadLine()
IF Trim(strLine) <> "" Then
'*** Rows ***'
dr = dt.NewRow
dr("CustomerID") = Split(strLine,",")(0)
dr("Name") = Split(strLine,",")(1)
dr("Email") = Split(strLine,",")(2)
dr("CountryCode") = Split(strLine,",")(3)
dr("Budget") = Split(strLine,",")(4)
dr("Used") = Split(strLine,",")(5)
dt.Rows.Add(dr)
End IF
Loop
StrWer.Close()
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("CustomerID") %></td>
<td><%#Container.DataItem("Name") %></td>
<td><%#Container.DataItem("Email") %></td>
<td align="center"><%#Container.DataItem("CountryCode") %></td>
<td align="right"><%#Container.DataItem("Budget") %></td>
<td align="right"><%#Container.DataItem("Used") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Screenshot
|