搜尋此網誌

2024年7月9日 星期二

dotnet CLI 加入 CsvHelper

緣起:


    這陣子都在學習怎麼在 Ubuntu 上操作 dotnet 的 CLI,今天在工作時有碰到需求要處理 csv 檔,後面是找到教學說,使用 CsvHelper 這個套件來處理。回家在看 microsoft 的 dotnet 文件,剛好學到 Nuget 套件的處理,所以想來動手操作個,順便紀錄 CsVHelper 的使用。


dotnet 專案加入套件:


    第一步是建個 console 的專案,我下

dotnet new console --use-program-main -o NugetTest

    來建立一個叫 NugetTest 的 Console 專案,然後用 vscode 來開啟專案資料㚒,開啟 terminal 視窗,照著這篇教學說的,輸入

dotnet add package CsvHelper
  
    它跑出這些訊息

Determining projects to restore...
  Writing /tmp/tmpAppbn8.tmp
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/lib/dotnet/sdk/8.0.105/trustedroots/codesignctl.pem'.
info : X.509 certificate chain validation will use the fallback certificate bundle at '/usr/lib/dotnet/sdk/8.0.105/trustedroots/timestampctl.pem'.
info : Adding PackageReference for package 'CsvHelper' into project '/home/birdshiu/Desktop/C#Project/NugetTest/NugetTest.csproj'.
info :   GET https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/index.json
info :   OK https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/index.json 209ms
info :   GET https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/0.12.0/2.13.4.json
info :   OK https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/0.12.0/2.13.4.json 770ms
info :   GET https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/2.13.5/9.0.0.json
info :   OK https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/2.13.5/9.0.0.json 193ms
info :   GET https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/9.0.1/21.1.0.json
info :   OK https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/9.0.1/21.1.0.json 780ms
info :   GET https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/21.1.1/33.0.1.json
info :   OK https://api.nuget.org/v3/registration5-gz-semver2/csvhelper/page/21.1.1/33.0.1.json 791ms
info : Restoring packages for /home/birdshiu/Desktop/C#Project/NugetTest/NugetTest.csproj...
info :   GET https://api.nuget.org/v3-flatcontainer/csvhelper/index.json
info :   OK https://api.nuget.org/v3-flatcontainer/csvhelper/index.json 779ms
info :   GET https://api.nuget.org/v3-flatcontainer/csvhelper/33.0.1/csvhelper.33.0.1.nupkg
info :   OK https://api.nuget.org/v3-flatcontainer/csvhelper/33.0.1/csvhelper.33.0.1.nupkg 14ms
info : Installed CsvHelper 33.0.1 from https://api.nuget.org/v3/index.json with content hash fev4lynklAU2A9GVMLtwarkwaanjSYB4wUqO2nOJX5hnzObORzUqVLe+bDYCUyIIRQM4o5Bsq3CcyJR89iMmEQ==.
info :   GET https://api.nuget.org/v3/vulnerabilities/index.json
info :   OK https://api.nuget.org/v3/vulnerabilities/index.json 16ms
info :   GET https://api.nuget.org/v3-vulnerabilities/2024.07.09.11.36.36/vulnerability.base.json
info :   GET https://api.nuget.org/v3-vulnerabilities/2024.07.09.11.36.36/2024.07.09.11.36.36/vulnerability.update.json
info :   OK https://api.nuget.org/v3-vulnerabilities/2024.07.09.11.36.36/vulnerability.base.json 14ms
info :   OK https://api.nuget.org/v3-vulnerabilities/2024.07.09.11.36.36/2024.07.09.11.36.36/vulnerability.update.json 37ms
info : Package 'CsvHelper' is compatible with all the specified frameworks in project '/home/birdshiu/Desktop/C#Project/NugetTest/NugetTest.csproj'.
info : PackageReference for package 'CsvHelper' version '33.0.1' added to file '/home/birdshiu/Desktop/C#Project/NugetTest/NugetTest.csproj'.
info : Writing assets file to disk. Path: /home/birdshiu/Desktop/C#Project/NugetTest/obj/project.assets.json
log  : Restored /home/birdshiu/Desktop/C#Project/NugetTest/NugetTest.csproj (in 5.02 sec).

    在專案裡就能 using CsvHelper 了


    用 dotnet list package 可以看到專案的 package

Project 'NugetTest' has the following package references
   [net8.0]: 
   Top-level Package      Requested   Resolved
   > CsvHelper            33.0.1      33.0.1 

    專案參考的 package 設定,可以在 {專案root}/obj/project.assets.json 看到。我注意到,那些 package 預設會裝到  /home/{你這個使用者}/.nuget/packages 裡頭


    在專案目錄下 dotnet remove package {package名稱} 可以把 package 的參考移除。


CsvHelper 逐行讀取 Csv 檔内容:


    參考的文章,我用 LibreOffice 弄一個 csv 檔出來


    它名字叫 test.csv,放在 Desktop。

    專案的 Program.cs 程式

namespace NugetTest;
using CsvHelper;
using CsvHelper.Configuration;
using CsvHelper.Configuration.Attributes;
using System.Globalization;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string sFilePath = "/home/birdshiu/Desktop/test.csv";
        
        CsvConfiguration configuration = new CsvConfiguration(CultureInfo.InvariantCulture)
        {
            HasHeaderRecord = true
        };

        using(StreamReader reader = new StreamReader(sFilePath))
        using(CsvReader csvReader = new CsvReader(reader, configuration))
        {
            IEnumerable<CsvClass> records = csvReader.GetRecords<CsvClass>();
            foreach(CsvClass record in records)
            {
                Console.WriteLine($"first:{record.Column1}, second:{record.Column2}, third:{record.Column3}");
            }
        }

    }

    class CsvClass{
        [Index(0)]
        public string? Column1{get;set;}
        [Index(1)]
        public string? Column2{get;set;}
        [Index(2)]
        public string? Column3{get;set;}
    }
}

    31~38 行 : 定義 csv 檔每一列的資料,只要使用  Index 的 Attribute,它就會自動把 column index 自動對應到 class 的 property 上。

    14~17 行 : csv 檔的設定,HasHeaderRecord 設成 true ,告訴它第一行是標頭。

    19~27 行 : 用 StreamReader 讀取 csv 檔,再把 StreamReader 丢入 CsvReader 的 Constructor 裡,呼叫 CsvReader 的 GetRecords 方法,它會回傳 IEnumerable,class 參數是 CsvClass。用 foreach 來遊歷每一列,由於我們有設定 HasHeaderRecord,所以第一列不會在裡面。

    最後輸入 dotnet run 來看輸出

birdshiu@birdshiu-VivoBook-ASUSLaptop-X415JP:~/Desktop/C#Project/NugetTest$ dotnet run
first:1, second:2, third:3
first:4, second:5, third:6
first:7, second:8, third:9

沒有留言:

張貼留言