C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C#操作CSV文件

C#操作CSV文件的详细教程

作者:工程师007

文章详细介绍了CSV文件的格式、读取和写入多种方式,包括使用StreamReader、TextFieldParser、CsvHelper库等,同时,还讨论了处理特殊字符、将CSV数据映射到对象以及注意事项,如文件路径和数据类型转换,并提到了性能优化的方法,需要的朋友可以参考下

一、CSV 格式详解

基本语法

编码格式

常见的 CSV 文件编码有 UTF - 8、GBK 等。在读写 CSV 文件时,需要确保指定正确的编码格式,否则可能会出现乱码。例如,在使用 StreamReaderStreamWriter 时,可以通过 Encoding 参数指定编码:

using (StreamReader reader = new StreamReader("data.csv", System.Text.Encoding.UTF8))
{
    // 读取操作
}

二、读取 CSV 文件的多种方式

(一)使用StreamReader逐行读取

原理 :通过 StreamReader 逐行读取 CSV 文件内容,然后对每一行进行处理,将字符串按逗号分隔成数组。

代码示例

using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        List<string[]> csvData = new List<string[]>();
        using (StreamReader reader = new StreamReader("data.csv"))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                // 将每一行按逗号分隔成数组
                string[] fields = line.Split(',');
                csvData.Add(fields);
            }
        }
        // 输出读取的数据
        foreach (string[] row in csvData)
        {
            foreach (string field in row)
            {
                Console.Write(field + "\t");
            }
            Console.WriteLine();
        }
    }
}

(二)使用TextFieldParser(需引用Microsoft.VisualBasic.dll组件)

  1. 原理TextFieldParser 是 .NET Framework 提供的一个专门用于解析文本文件的类,它可以更好地处理 CSV 文件中包含特殊字符的字段。
  2. 代码示例
using System;
using Microsoft.VisualBasic.FileIO;

class Program
{
    static void Main()
    {
        using (TextFieldParser parser = new TextFieldParser("data.csv"))
        {
            parser.TextFieldType = FieldType.Delimited;
            parser.SetDelimiters(",");
            while (!parser.EndOfData)
            {
                try
                {
                    string[] fields = parser.ReadFields();
                    foreach (string field in fields)
                    {
                        Console.Write(field + "\t");
                    }
                    Console.WriteLine();
                }
                catch (MalformedLineException ex)
                {
                    Console.WriteLine("行 {0} 格式错误: {1}", parser.LineNumber, ex.Message);
                }
            }
        }
    }
}
  1. 优点 :能够正确处理字段中包含逗号、引号等特殊字符的情况。
  2. 缺点 :需要引用 Microsoft.VisualBasic.dll 组件。

(三)使用第三方库(如 CsvHelper)

Install-Package CsvHelper
using System;
using System.Collections.Generic;
using System.IO;
using CsvHelper;
using CsvHelper.Configuration;

class Program
{
    static void Main()
    {
        using (StreamReader reader = new StreamReader("data.csv"))
        using (CsvReader csv = new CsvReader(reader, new CsvConfiguration(System.Globalization.CultureInfo.InvariantCulture)))
        {
            var records = csv.GetRecords<Person>().ToList();
            foreach (Person person in records)
            {
                Console.WriteLine($"姓名: {person.Name}, 年龄: {person.Age}, 性别: {person.Gender}");
            }
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}
  1. 优点 :功能强大,易于使用,支持对象映射和高级配置。
  2. 缺点 :需要引入外部依赖。

三、写入 CSV 文件的多种方式

(一)使用StreamWriter写入

  1. 原理 :将二维数据数组或列表转换为字符串,按行写入到 CSV 文件中。
  2. 代码示例
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string[][] data = new string[][]
        {
            new string[] {"姓名", "年龄", "性别"},
            new string[] {"张三", "25", "男"},
            new string[] {"李四", "30", "女"}
        };
        using (StreamWriter writer = new StreamWriter("data.csv"))
        {
            foreach (string[] row in data)
            {
                // 将数组元素用逗号连接成一行
                writer.WriteLine(string.Join(",", row));
            }
        }
    }
}

(二)使用StringBuilder构建内容后写入

  1. 原理 :先用 StringBuilder 构建整个 CSV 内容,最后一次性写入文件,减少文件操作次数,尤其适用于大量数据写入。
  2. 代码示例
using System;
using System.IO;
using System.Text;

class Program
{
    static void Main()
    {
        string[][] data = new string[][]
        {
            new string[] {"姓名", "年龄", "性别"},
            new string[] {"张三", "25", "男"},
            new string[] {"李四", "30", "女"}
        };
        StringBuilder sb = new StringBuilder();
        foreach (string[] row in data)
        {
            sb.AppendLine(string.Join(",", row));
        }
        File.WriteAllText("data.csv", sb.ToString());
    }
}
  1. 优点 :提高写入效率,适合大量数据写入。
  2. 缺点 :无法自动处理字段中的特殊字符。

(三)使用第三方库(如 CsvHelper)写入

  1. 原理 :利用 CsvHelper 提供的简便 API,将对象列表写入 CSV 文件,自动处理字段中的特殊字符。
  2. 代码示例
using System;
using System.Collections.Generic;
using System.IO;
using CsvHelper;

class Program
{
    static void Main()
    {
        List<Person> persons = new List<Person>
        {
            new Person { Name = "张三", Age = 25, Gender = "男" },
            new Person { Name = "李四", Age = 30, Gender = "女" }
        };
        using (StreamWriter writer = new StreamWriter("data.csv"))
        using (CsvWriter csv = new CsvWriter(writer, System.Globalization.CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(persons);
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}
  1. 优点 :功能强大,易于使用,自动处理特殊字符。
  2. 缺点 :需要引入外部依赖。

四、CSV 数据的解析与处理

(一)处理字段中的特殊字符

  1. 引号包围字段 :如果字段中包含逗号、引号或换行符,需要用双引号将字段包围起来。如果字段本身包含双引号,则需要用两个双引号表示一个双引号。
  2. 代码示例 - 写入包含特殊字符的字段
using System;
using System.IO;

class Program
{
    static void Main()
    {
        string[][] data = new string[][]
        {
            new string[] {"姓名", "年龄", "爱好"},
            new string[] {"张三", "25", "读书, 旅行"},
            new string[] {"李四", "30", "打篮球\" \"排球"}
        };
        using (StreamWriter writer = new StreamWriter("data.csv"))
        {
            foreach (string[] row in data)
            {
                for (int i = 0; i < row.Length; i++)
                {
                    // 如果字段中包含逗号、引号或换行符,用双引号包围
                    if (row[i].Contains(",") || row[i].Contains("\"") || row[i].Contains("\n") || row[i].Contains("\r"))
                    {
                        // 将字段中的双引号替换为两个双引号
                        row[i] = "\"" + row[i].Replace("\"", "\"\"") + "\"";
                    }
                    writer.Write(row[i]);
                    if (i < row.Length - 1)
                    {
                        writer.Write(",");
                    }
                }
                writer.WriteLine();
            }
        }
    }
}

(二)将 CSV 数据映射到对象

  1. 定义数据类 :根据 CSV 文件的结构定义一个对应的类,方便对数据进行操作。
  2. 代码示例
using System;
using System.Collections.Generic;
using System.IO;

class Program
{
    static void Main()
    {
        List<Person> persons = new List<Person>();
        using (StreamReader reader = new StreamReader("data.csv"))
        {
            // 跳过标题行
            reader.ReadLine();
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                string[] fields = line.Split(',');
                Person person = new Person
                {
                    Name = fields[0],
                    Age = int.Parse(fields[1]),
                    Gender = fields[2]
                };
                persons.Add(person);
            }
        }
        // 输出对象数据
        foreach (Person person in persons)
        {
            Console.WriteLine($"姓名: {person.Name}, 年龄: {person.Age}, 性别: {person.Gender}");
        }
    }
}

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
}

五、注意事项

文件路径问题    

if (!File.Exists("data.csv"))
{
    Console.WriteLine("文件不存在!");
}

数据类型转换问题 

int age;
if (int.TryParse(fields[1], out age))
{
    person.Age = age;
}
else
{
    Console.WriteLine("年龄数据格式错误!");
}

性能优化

以上就是C#操作CSV文件的详细教程的详细内容,更多关于C#操作CSV文件的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文