首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 讀取文字檔資料繫結至 DataView 實作

     編輯:ASP.NET 基礎

適用情境

文字檔(CSV/TSV/固定寬度)匯入系統,需快速轉為 DataTable/DataView 供 GridView/Repeater 繫結顯示。

通用解析方法

public static DataView ParseTextFileToDataView(string filePath, char delimiter = '\t', Encoding encoding = null) 
{ 
    encoding ??= Encoding.GetEncoding("GB2312"); // 或 UTF8 
    var dt = new DataTable(); 
    
    using (var reader = new StreamReader(filePath, encoding)) 
    { 
        // 讀取標題列建立欄位 
        string headerLine = reader.ReadLine(); 
        if (string.IsNullOrEmpty(headerLine)) return new DataView(dt); 
        
        string[] headers = headerLine.Split(delimiter); 
        foreach (string h in headers) 
        { 
            dt.Columns.Add(h.Trim(), typeof(string)); 
        } 
        
        // 逐行讀取資料 
        string line; 
        while ((line = reader.ReadLine()) != null) 
        { 
            if (string.IsNullOrWhiteSpace(line)) continue; 
            
            string[] fields = line.Split(delimiter); 
            var row = dt.NewRow(); 
            for (int i = 0; i < headers.Length && i < fields.Length; i++) 
            { 
                row[i] = fields[i].Trim(); 
            } 
            dt.Rows.Add(row); 
        } 
    } 
    return new DataView(dt); 
}

使用範例

protected void btnImport_Click(object sender, EventArgs e) 
{ 
    if (!fuFile.HasFile) return; 
    
    string path = Server.MapPath($"~/Temp/{Guid.NewGuid()}{Path.GetExtension(fuFile.FileName)}"); 
    fuFile.SaveAs(path); 
    
    try 
    { 
        // Tab 分隔 
        var dv = ParseTextFileToDataView(path, '\t'); 
        gvData.DataSource = dv; 
        gvData.DataBind(); 
    } 
    finally 
    { 
        if (File.Exists(path)) File.Delete(path); 
    } 
}

進階:使用 TextFieldParser (Microsoft.VisualBasic.FileIO)

內建支援引號包裹、逗號跳脫、多行欄位等標準 CSV 規範。

using Microsoft.VisualBasic.FileIO; 

public static DataTable ParseCsvWithParser(string filePath) 
{ 
    var dt = new DataTable(); 
    using (var parser = new TextFieldParser(filePath, Encoding.GetEncoding("GB2312"))) 
    { 
        parser.TextFieldType = FieldType.Delimited; 
        parser.SetDelimiters(","); 
        parser.HasFieldsEnclosedInQuotes = true; 
        
        string[] headers = parser.ReadFields(); 
        foreach (string h in headers) dt.Columns.Add(h, typeof(string)); 
        
        while (!parser.EndOfData) 
        { 
            string[] fields = parser.ReadFields(); 
            dt.Rows.Add(fields); 
        } 
    } 
    return dt; 
}

效能比較

方法優點缺點適用場景
StreamReader + Split零依賴、記憶體效率好不支援引號/換行欄位簡單 TSV、固定格式
TextFieldParser標準 CSV 相容、自動處理跳脫需參考 Microsoft.VisualBasic標準 CSV、使用者匯出檔
CsvHelper (NuGet)強型別對應、效能極佳、功能豐富第三方套件正式專案、大量資料
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved