Read CSV file with CSVHelper C#


24/08/2021- duocnt    1333 Views    

CÁC BƯỚC THỰC HIỆN

  1. Tạo Console project.
  2. Cài đặt CSVHelper pakage.
  3. Tạo class để map dữ liệu.
  4. Tạo class đọc dữ liệu.
  5. Đọc dữ liệu từ hàm main.
  6. Kết quả.


TÀI LIỆU CHÍNH THỨC

https://joshclose.github.io/CsvHelper/getting-started/

THỰC HIỆN

1 - Tạo Console project.


2 - Cài đặt CSVHelper package.

Có 2 cách để install package CSVHelper vào project.

  • Install từ "Package Manager Console".


  • Install từ "Manage NuGet Packages".



3 - Tạo Class để map dữ liệu.

  • Trong hướng dẫn này, mình sẽ sử dụng CSV URL:
     https://support.spatialkey.com/wp-content/uploads/2021/02/TechCrunchcontinentalUSA.csv.
  • Dữ liệu từ CSV trên khi xuất ra excel sẽ như sau:


  • Do đó, với cấu trúc dữ liệu như vậy, chúng ta cần tạo 1 class tương đương để map dữ liệu khi sử dụng CSVHelper đọc dữ liệu.
  • Trong bài viết này, mình sẽ tạo class với name "TechCrunchcontinentalUSA".


4 - Tạo class đọc dữ liệu.

  • Chúng ta sẽ tạo 1 class với những phương thức đọc dữ liệu.
  • Trong hướng dẫn này mình tạo class với name "ReadCSV".


  • Tạo phương thức khởi tạo và thuộc tính URL cho class ReadCSV.


  • Tạo phương thức để đọc dữ liệu từ CSV URL.
  • Trong hướng dẫn này, mình tạo phương thức ReadCSVData.
        public IEnumerable<TechCrunchcontinentalUSA> ReadCSVData()
        {
            //Declare variables
            IEnumerable<TechCrunchcontinentalUSA> _techCrunchcontinentalUSAs = null;
            HttpWebRequest _httpWebRequest = null;
            HttpWebResponse _httpWebResponse =null;
            StreamReader _streamReader = null;
            CsvReader _csvReader = null;
 
            //Make request to URL and retrieve data from csv.
            _httpWebRequest = (HttpWebRequest)WebRequest.Create(this.url);
            _httpWebResponse = (HttpWebResponse) _httpWebRequest.GetResponse();
            _streamReader = new StreamReader(_httpWebResponse.GetResponseStream());
            _csvReader = new CsvReader(_streamReader, CultureInfo.InvariantCulture);
            _techCrunchcontinentalUSAs = _csvReader.GetRecords<TechCrunchcontinentalUSA>();
 
            //return
            return _techCrunchcontinentalUSAs;
        }


5 - Đọc dữ liệu từ hàm main.


        static void Main(string[] args)
        {
            string URL = "https://support.spatialkey.com/wp-content/uploads/2021/02/TechCrunchcontinentalUSA.csv";
            ReadCSV readCSV = new ReadCSV();
            readCSV.URL = URL;
 
            IEnumerable<TechCrunchcontinentalUSA> techCrunchcontinentalUSAs = readCSV.ReadCSVData();
            foreach(TechCrunchcontinentalUSA techCrunchcontinentalUSA in techCrunchcontinentalUSAs)
            {
                Console.WriteLine(techCrunchcontinentalUSA.company);
            }
            Console.ReadLine();
        }


6 - KẾT QUẢ.


Góp ý kiến

;
;