(C#) ASP.NET Read CSV file |
(C#) 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="C#" Debug="true" %>
<script runat="server">
void Page_Load(object sender,EventArgs e)
{
DataTable dt;
//*** DataTable ***//
dt = ReadCSV(); //*** Convert CSV to DataTable ***//
//*** BindData to Repeater ***//
myRepeater.DataSource = dt;
myRepeater.DataBind();
}
//*** CSV & DataTable ***//
protected DataTable ReadCSV()
{
DataTable dt = new DataTable();
DataRow dr;
//*** 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");
StreamReader StrWer;
String strLine;
StrWer = File.OpenText(Server.MapPath("csv/customer.csv")) ;
while (StrWer.EndOfStream == false)
{
strLine = StrWer.ReadLine();
if(strLine.Trim() != "")
{
//*** Rows ***//
dr = dt.NewRow();
dr["CustomerID"] = strLine.Split(',')[0];
dr["Name"] = strLine.Split(',')[1];
dr["Email"] = strLine.Split(',')[2];
dr["CountryCode"] = strLine.Split(',')[3];
dr["Budget"] = strLine.Split(',')[4];
dr["Used"] = strLine.Split(',')[5];
dt.Rows.Add(dr);
}
}
StrWer.Close();
return dt; //*** Return DataTable ***//
}
</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"><%# DataBinder.Eval(Container.DataItem, "CustomerID") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Name") %></td>
<td><%# DataBinder.Eval(Container.DataItem, "Email") %></td>
<td align="center"><%# DataBinder.Eval(Container.DataItem, "CountryCode") %></td>
<td align="right"><%# DataBinder.Eval(Container.DataItem, "Budget") %></td>
<td align="right"><%# DataBinder.Eval(Container.DataItem, "Used") %></td>
</tr>
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Screenshot
|