(C#) ASP.NET CSV & ADO.NET - System.Data.OleDb |
(C#) ASP.NET CSV & ADO - System.Data.OleDb ตัวอย่างนี้จะเป็นการเปิดไฟล์ CSV โดยใช้ ADO.NET และ NameSpace ของ System.Data.OleDb ผ่าน Driver ชื่อ Provider=Microsoft.Jet.OLEDB.4.0 การใช้ 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"
AspNetAdoReadCSV.aspx
<%@ Import Namespace="System.Data"%>
<%@ Import Namespace="System.Data.OleDb"%>
<%@ Page Language="C#" Debug="true" %>
<script runat="server">
void Page_Load(object sender,EventArgs e)
{
DataTable dt;
//*** Csv to DataTable ***//
dt = CsvCreateDataTable();
//*** BindData to Repeater ***//
myRepeater.DataSource = dt;
myRepeater.DataBind();
}
//*** DataTable ***//
protected DataTable CsvCreateDataTable()
{
OleDbConnection objConn = new OleDbConnection();
OleDbDataAdapter dtAdapter;
DataTable dt = new DataTable();
String strConnString;
strConnString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source="+Server.MapPath("csv/") +
";Extended Properties='TEXT;HDR=Yes;FMT=Delimited;Format=Delimited(,)'";
objConn = new OleDbConnection(strConnString);
objConn.Open();
String strSQL;
strSQL = "SELECT * FROM customer.csv";
dtAdapter = new OleDbDataAdapter(strSQL, objConn);
dtAdapter.Fill(dt);
dtAdapter = null;
objConn.Close();
objConn = null;
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
|