Web Developer
ASP.NET, Visual Basic.NET, C#, TSQL, HTML, CSS, PHP, JavaScript, WordPress, WooCommerce
Windows Server, Internet Information Server, SQL Server, Hyper-V

Работа с CSV файлами с помощью библиотеки CsvHelper (Обновлено!)

Библиотека CsvHelper – быстрый и простой в использовании способ чтения и записи пользовательских объектов в csv-файлы

Imports CsvHelper
Imports System.IO

...

Public Class MyDataClass
    Public Property FieldA As Integer
    Public Property FieldB As String
     ....
    Public Property FieldX As String
End Class

...

' *** Пишем в CSV файл  ***
Dim MyData1 = New MyDataClass With {.FieldA = 1, .FieldB = "2", .FieldX = "X"}
Using writer = New StreamWriter(Server.MapPath("~/AppData/Output.csv"))
    Dim csv = New CsvWriter(writer)
    csv.Configuration.Encoding = Encoding.UTF8
    csv.WriteHeader(Of MyDataClass)()
    csv.WriteRecord(MyData) 
End Using


' *** Читаем из CSV файла ***
Using reader = New StreamReader(Server.MapPath("~/AppData/Output.csv"), True)
    Dim csv = New CsvReader(reader)
    csv.Configuration.IgnoreHeaderWhiteSpace = True  
    'csv.Configuration.Delimiter = ";"

    'CSVReader will now read the whole file into an enumerable
    Dim records As IEnumerable(Of MyDataClass) = csv.GetRecords(Of MyDataClass)().ToList()

    'First 5 records in CSV file will be printed 
    'For Each record As DataRecord In records.Take(5)

    For Each record In records.Take(3)
        Response.Write(record.FieldA, record.FieldB, record.FieldX)
    Next
End Using


Ссылки по теме:

Share

You may also like...

Добавить комментарий

Ваш адрес email не будет опубликован.