使用 WeihanLi.Npoi 操作 CSV


使用 WeihanLi.Npoi 操作 CSV

Intro

最近發現 csv 文件在很多情況下都在使用,而且經過大致了解,csv 格式簡單,相比 excel 文件要小很多,讀取也很是方便,而且也很通用,微軟的 ml.net示例項目 用來訓練模型的數據也是使用的 csv 來保存的,最近又發現使用 jmeter 來測試網站的性能,也可以用 csv 來參數化請求,csv 文件操作的重要性由此可見。

此前做了一個 NPOI 的擴展 WeihanLi.Npoi,支持.net45 以及 .netstandard2.0及以上,主要是對 excel 文件的操作,於是打算再增加一些對csv的操作。

csv 操作API

/// <summary>
/// save to csv file
/// </summary>
public static int ToCsvFile(this DataTable dt, string filePath);
public static int ToCsvFile(this DataTable dataTable, string filePath, bool includeHeader);

/// <summary>
/// to csv bytes
/// </summary>
public static byte[] ToCsvBytes(this DataTable dt);
public static byte[] ToCsvBytes(this DataTable dataTable, bool includeHeader);

/// <summary>
/// convert csv file data to dataTable
/// </summary>
/// <param name="filePath">csv file path</param>
public static DataTable ToDataTable(string filePath);

/// <summary>
/// convert csv file data to entity list
/// </summary>
/// <param name="filePath">csv file path</param>
public static List<TEntity> ToEntityList<TEntity>(string filePath) where TEntity : new();

/// <summary>
/// save to csv file
/// </summary>
public static int ToCsvFile<TEntity>(this IEnumerable<TEntity> entities, string filePath);
public static int ToCsvFile<TEntity>(this IEnumerable<TEntity> entities, string filePath, bool includeHeader);

/// <summary>
/// to csv bytes
/// </summary>
public static byte[] ToCsvBytes<TEntity>(this IEnumerable<TEntity> entities) => ToCsvBytes(entities, true);
public static byte[] ToCsvBytes<TEntity>(this IEnumerable<TEntity> entities, bool includeHeader);

通過上面的方法,即可方便的將一個 IEnumerable 對象或者是DataTable 導出為 csv 文件或者或者 csv 文件的字節數組,也可將 csv 文件轉換為 DataTable 或者 List 對象。

並且我於昨天優化了 csv 轉成 list 對象的操作,並且支持了簡單類型(比如int/long等 )的直接導出

Sample

var entities = new List<TestEntity>()
{
    new TestEntity()
    {
        PKID = 1,
        SettingId = Guid.NewGuid(),
        SettingName = "Setting1",
        SettingValue = "Value1"
    },
    new TestEntity()
    {
        PKID=2,
        SettingId = Guid.NewGuid(),
        SettingName = "Setting2",
        SettingValue = "Value2"
    },
};
var csvFilePath = $@"{Environment.GetEnvironmentVariable("USERPROFILE")}\Desktop\temp\test\test.csv";
entities.ToCsvFile(csvFilePath);
var entities1 = CsvHelper.ToEntityList<TestEntity>(csvFilePath);

entities.ToExcelFile(csvFilePath.Replace(".csv", ".xlsx"));

var vals = new[] { 1, 2, 3, 5, 4 };
vals.ToCsvFile(csvFilePath);

var numList = CsvHelper.ToEntityList<int>(csvFilePath);
Console.WriteLine(numList.StringJoin(","));

更多詳情可參考示例:https://github.com/WeihanLi/WeihanLi.Npoi/blob/dev/samples/DotNetCoreSample/Program.cs

More

導入導出的時候如果根據需要配置要導出的屬性以及順序,和之前導出 Excel 相似,需要配置一下 ,目前和 Excel 導入導出共享配置,配置方式支持 Attribute 或者 FluentAPI 兩種方式(不支持Excel的一些配置如Author,title、subject以及sheet等信息),示例如下:

// Attribute config
public class TestEntity
{
    public string Username { get; set; }

    [Column(IsIgnored = true)]
    public string PasswordHash { get; set; }

    public decimal Amount { get; set; } = 1000M;

    public string WechatOpenId { get; set; }

    public bool IsActive { get; set; }
}


// Fluent API
var setting = ExcelHelper.SettingFor<TestEntity>();
// ExcelSetting
setting.HasAuthor("WeihanLi")
    .HasTitle("WeihanLi.Npoi test")
    .HasDescription("")
    .HasSubject("");

setting.Property(_ => _.SettingId)
    .HasColumnIndex(0);

setting.Property(_ => _.SettingName)
    .HasColumnIndex(1);

setting.Property(_ => _.DisplayName)
    .HasColumnIndex(2);

setting.Property(_ => _.SettingValue)
    .HasColumnIndex(3);

setting.Property(_ => _.CreatedTime)
    .HasColumnIndex(5);

setting.Property(_ => _.CreatedBy)
    .HasColumnIndex(4);

setting.Property(_ => _.UpdatedBy).Ignored();
setting.Property(_ => _.UpdatedTime).Ignored();
setting.Property(_ => _.PKID).Ignored();

更多配置詳情參考:https://github.com/WeihanLi/WeihanLi.Npoi#define-custom-mapping-and-settings

End

如果有 csv 文件操作的需求,可以嘗試使用它,如果不能滿足你的需求歡迎來給我提 issue


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM