如何在 C#(、NET Core)中不使用任何包导出 CSV?

问题描述 投票:0回答:1

如何在不使用 .NET core 中的任何包的情况下创建结构良好的 csv 文件。

并使用类 Keys 作为标题。

    public class TestArray
    {
        public string LastName{ get; set; }
        public string FirstName { get; set; }
        public string Age { get; set; }
        public bool MoNumber { get; set; }
    }

我尝试使用

CsvHelper
包,它工作得很好,但我想导出 csv 文件而不使用任何包。

c# .net asp.net-core .net-core export-to-csv
1个回答
0
投票

试试这个:

第 1 步:创建数据类

您已经定义了

TestArray
类。但是,
MoNumber
的属性类型可能存在拼写错误或问题。假设它是一个字符串或类似的东西来表示手机号码,我会在这里更正它:

public class TestArray
{
    public string LastName { get; set; }
    public string FirstName { get; set; }
    public string Age { get; set; }
    public string MoNumber { get; set; }  // Assuming this should be a string.
}

第 2 步:创建将数据写入 CSV 的方法

以下是将

TestArray
对象列表写入 CSV 文件的方法:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;

public class CsvExporter
{
    public static void WriteCsv<T>(IEnumerable<T> items, string path)
    {
        Type itemType = typeof(T);
        var props = itemType.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                            .Where(pi => pi.PropertyType == typeof(string) || pi.PropertyType == typeof(bool) || pi.PropertyType.IsPrimitive)
                            .ToArray();

        using (var writer = new StreamWriter(path))
        {
            // Writing header (property names)
            writer.WriteLine(string.Join(",", props.Select(p => p.Name)));

            // Writing data
            foreach (var item in items)
            {
                writer.WriteLine(string.Join(",", props.Select(p => GetValue(p, item))));
            }
        }
    }

    private static string GetValue(PropertyInfo propertyInfo, object obj)
    {
        var value = propertyInfo.GetValue(obj, null);
        return value?.ToString().Replace(",", ";");  // Escape commas in data
    }
}

第三步:使用方法

您现在可以使用此方法创建 CSV 文件。以下是如何使用此方法的示例:

public class Program
{
    static void Main(string[] args)
    {
        List<TestArray> list = new List<TestArray>
        {
            new TestArray { LastName = "Smith", FirstName = "John", Age = "30", MoNumber = "9876543210" },
            new TestArray { LastName = "Doe", FirstName = "Jane", Age = "25", MoNumber = "1234567890" }
        };

        CsvExporter.WriteCsv(list, "test.csv");
        Console.WriteLine("CSV file has been written.");
    }
}

备注:

  • 确保您的属性是可以直接转换为字符串的简单类型。如果您有复杂的类型或需要特殊的格式,您可能需要相应地调整
    GetValue
    方法。
  • 此示例处理基本的 CSV 写入场景。如果您有特殊字符、多行值或其他 CSV 复杂性的要求,您可能需要扩展逻辑以正确处理此类情况。
© www.soinside.com 2019 - 2024. All rights reserved.