17370845950

.NET怎么将CSV文件读取到DataTable中
使用TextFieldParser可稳定读取CSV到DataTable,支持复杂格式。首先添加Microsoft.VisualBasic引用,用TextFieldParser设置逗号分隔,首行作列名,逐行读取数据并填充DataTable,能正确处理引号、换行和逗号;简单CSV可用StreamReader加Split解析;注意文件编码、内存占用,大文件应逐行处理,推荐UTF8编码,复杂场景优先选TextFieldParser或CsvHelper库。

在 .NET 中,可以使用 StreamReader 结合 TextFieldParser(来自 Microsoft.VisualBasic.FileIO 命名空间)或手动解析的方式将 CSV 文件读取到 DataTable 中。推荐使用 TextFieldParser,因为它能正确处理包含逗号、换行或引号的字段。

使用 TextFieldParser 读取 CSV 到 DataTable

这是最稳定且推荐的方法,尤其适用于格式复杂的 CSV 文件。

步骤:

  • 添加对 Microsoft.VisualBasic 的引用(即使在 C# 项目中也可用)
  • 使用 TextFieldParser 设置分隔符并逐行读取
  • 第一行通常作为列名
  • 后续行作为数据插入 DataTable

示例代码:

using System.Data;
using Microsoft.VisualBasic.FileIO;

DataTable LoadCsvToDataTable(string filePath) { DataTable dt = new DataTable();

using (TextFieldParser parser = new TextFieldParser(filePath))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");

    // 读取第一行作为列名
    if (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields();
        foreach (string field in fields)
        {
            dt.Columns.Add(field);
        }
    }

    // 读取剩余行作为数据
    while (!parser.EndOfData)
    {
        string[] fields = parser.ReadFields();
        dt.Rows.Add(fields);
    }
}

return dt;

}

手动使用 StreamReader 解析(简单 CSV)

如果 CSV 文件格式简单(无引号包裹的逗号或换行),可以直接用 StreamReaderSplit(',')

示例代码:

using System.IO;
using System.Data;

DataTable LoadCsvSimple(string filePath) { DataTable dt = new DataTable(); string[] lines = File.ReadAllLines(filePath);

if (lines.Length == 0) return dt;

// 第一行作为列名
string[] headers = lines[0].Split(',');
foreach (string header in headers)
{
    dt.Columns.Add(header);
}

// 添加数据行
for (int i = 1; i < lines.Length; i++)
{
    string[] data = lines[i].Split(',');
    dt.Rows.Add(data);
}

return dt;

}

注意事项

实际使用时需要注意以下几点:

  • CSV 文件编码问题:建议使用 new StreamReader(filePath, Encoding.UTF8) 明确指定编码
  • 字段中包含逗号时(如 "Smith, John"),必须用 TextFieldParser 才能正确解析
  • 大文件建议逐行读取,避免一次性加载到内存
  • 可考虑使用第三方库如 CsvHelper,功能更强大

基本上就这些。对于大多数场景,使用 TextFieldParser 是最稳妥的选择。