در این مقاله نحوه خواندن یک فایل CSV با استفاده از سی شارپ را خواهیم آموخت. در فایل CSV ردیف اول شامل سرصفحه ها و ردیف های دیگر حاوی بقیه داده ها هستند.
بیا شروع کنیم،
- پس از ایجاد یک وب سایت جدید، یک صفحه وب ReadCSV.aspx اضافه کنید.
- برای انتخاب فایل یک کنترل آپلود فایل اضافه کنید.
- اضافه کردن دکمه ارسال فایل انتخاب شده را بخوانید.
- برای دیدن داده های فایل CSV، نمای شبکه ای اضافه کنید.
ReadCSV.aspx
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
<asp:Panel ID="PanelMain" runat="server">
<br />
<table style="width: 44%;">
<tr>
<td style="width: 84px">Select File:</td>
<td style="width: 231px">
<asp:FileUpload ID="FileUpload1" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="* required" ControlToValidate="FileUpload1" ForeColor="Red" ValidationGroup="validation">
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td style="width: 84px"> </td>
<td style="width: 231px"> </td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="btnUpload" runat="server" Text="Upload" ValidationGroup="validation" OnClick="btnUpload_Click" />
</td>
</tr>
</table>
<br />
<asp:GridView ID="GridView1" runat="server"></asp:GridView>
<br />
<asp:Label ID="lblerror" runat="server" />
</asp:Panel>
</asp:Content>
ReadCSV.aspx.cs
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ReadCSV: System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {}
protected void btnUpload_Click(object sender, EventArgs e) {
try {
DataTable dt = new DataTable();
dt = ReadCsvFile();
GridView1.DataSource = dt;
GridView1.DataBind();
} catch (Exception ex) {
lblerror.Text = ex.Message;
}
}
public DataTable ReadCsvFile() {
DataTable dtCsv = new DataTable();
string Fulltext;
if (FileUpload1.HasFile) {
string FileSaveWithPath = Server.MapPath("\Files\Import" + System.DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".csv");
FileUpload1.SaveAs(FileSaveWithPath);
using(StreamReader sr = new StreamReader(FileSaveWithPath)) {
while (!sr.EndOfStream) {