Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use CsvHelper

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces how to use CsvHelper, has a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.

CsvHelper is a. Net library that reads and writes CSV files. You can download CsvHelper from Visual Studio's package manager. Automatic mapping definition: when no mapping file is provided, the default is automatic mapping, which is mapped sequentially to the attributes of the class.

GitHub address

Read all records var csv = new CsvReader (textReader); var records = csv.GetRecords (); / / Map CSV records to MyClass, and the returned records is an IEnumerable object

If you want to customize the mapping relationship, you can see the mapping section below.

Because records is an IEnumerable object, a record is returned only when it is accessed, and one record is returned for each visit. If you want to access like a list, you can do the following:

Var csv = new CsvReader (textReader); var records = csv.GetRecords () .ToList (); read the record manually

You can read each row of data in a row loop.

Var csv = new CsvReader (textReader); while (csv.Read ()) {var record = csv.GetRecord ();} read separate fields var csv = new CsvReader (textReader); while (csv.Read ()) {var intField = csv.GetField (0); var stringField = csv.GetField (1); var boolField = csv.GetField ("HeaderName");}

If the type of read may be different than expected, you can use TryGetField

Var csv = new CsvReader (textReader); while (csv.Read ()) {int intField; if (! csv.TryGetField (0, out intField)) {/ / Do something when it can't convert. }} parsing

You can use CsvParser if you want each line to be returned as a string.

Var parser = new CsvParser (textReader); while (true) {var row = parser.Read (); / / row is a string if (row = = null) {break;}} write to all records var csv = new CsvWriter (textWriter); csv.WriteRecords (records); var csv = new CsvWriter (textWriter); foreach (var item in list) {csv.WriteRecord (item);} var csv = new CsvWriter (textWriter) Foreach (var item in list) {csv.WriteField ("a"); csv.WriteField (2); csv.WriteField (true); csv.NextRecord ();} mapping automatically

When no mapping file is provided, the default is automatic mapping, which is mapped sequentially to the attributes of the class. If the property is a custom class, it will continue to fill in the properties of the custom class in turn. If a circular reference occurs, the automatic mapping stops.

Manual mapping

If the CSV file does not exactly match the custom class, you can define a matching class to handle it.

Public sealed class MyClassMap: CsvClassMap {public MyClassMap () {Map (m = > m.Id); Map (m = > m.Name);}} this article is referenced by tangyikejun translation

If the property is a custom class that corresponds to multiple columns in the CSV file, you can use reference mapping.

Public sealed class PersonMap: CsvClassMap {public PersonMap () {Map (m = > m.Id); Map (m = > m.Name); References (m = > m.Address);}} public sealed class AddressMap: CsvClassMap {public AddressMap () {Map (m = > m.Street); Map (m = > m.City); Map (m = > m.State); Map (m = > m.Zip) }} subscript assignment

You can specify the mapping through the column subscript

Public sealed class MyClassMap: CsvClassMap {public MyClassMap () {Map (m = > m.Id). Index (0); Map (m = > m.Name). Index (1);}} column name

You can also specify the mapping by column name, which requires the csv file to have a header record, that is, the column name of the first row of records

Public sealed class MyClassMap: CsvClassMap {public MyClassMap () {Map (m = > m.Id). Name ("The Id Column"); Map (m = > m.Name). Name ("The Name Column");}} same name processing public sealed class MyClassMap: CsvClassMap {public MyClassMap () {Map (m = > m.FirstName). Name ("Name"). NameIndex (0) Map (m = > m.LastName). Name ("Name"). NameIndex (1);}} default value public sealed class MyClassMap: CsvClassMap {public override void MyClassMap () {Map (m = > m.Id). Index (0). Default (- 1); Map (m = > m.Name). Index (1). Default ("Unknown") }} Type conversion public sealed class MyClassMap: CsvClassMap {public MyClassMap () {Map (m = > m.Id). Index (0). TypeConverter ();}} optional type conversion

The default converter handles most of the type conversions, but sometimes we may need to make some small changes, which can be tried with optional type conversions.

Public sealed class MyClassMap: CsvClassMap {public MyClassMap () {Map (m = > m.Description). Index (0). TypeConverterOption (CultureInfo.InvariantCulture); / / Map (m = > m.TimeStamp). Index (1). TypeConverterOption (DateTimeStyles.AdjustToUniversal); / / time format conversion Map (m = > m.Cost). Index (2). TypeConverterOption (NumberStyles.Currency) / / numeric type conversion Map (m = > m.CurrencyFormat). Index (3). TypeConverterOption ("C"); Map (m = > m.BooleanValue). Index (4). TypeConverterOption (true, "sure"). TypeConverterOption (false, "nope") / / content conversion}} ConvertUsingpublic sealed class MyClassMap: CsvClassMap {public MyClassMap () {/ / constant Map (m = > m.Constant). ConvertUsing (row = > 3); / / aggregate the two columns together Map (m = > m.Aggregate). ConvertUsing (row = > row.GetField (0) + row.GetField (1)); / / Collection with a single value. Map (m = > m.Names). ConvertUsing (row = > new List {row.GetField ("Name")}); / / Just about anything. Map (m = > m.Anything). ConvertUsing (row = > {/ / You can do anything you want in a block. / / Just make sure to return the same type as the property. });}} runtime mapping

You can create mappings at run time.

Var customerMap = new DefaultCsvClassMap (); / / mapping holds the Property-csv column mapping foreach (string key in mapping.Keys) {var columnName = mapping [key] .ToString (); if (! String.IsNullOrEmpty (columnName)) {var propertyInfo = typeof (Customer). GetType (). GetProperty (key); var newMap = new CsvPropertyMap (propertyInfo); newMap.Name (columnName); customerMap.PropertyMaps.Add (newMap);} csv.Configuration.RegisterClassMap (CustomerMap) In this article, the tangyikejun translation configuration allows the annotation / / Default valuecsv.Configuration.AllowComments = false; to automatically map var generatedMap = csv.Configuration.AutoMap (); cache

Caching of reads and writes in TextReader or TextWriter

/ / Default valuecsv.Configuration.BufferSize = 2048; comment

The line that is commented out will not be loaded

/ / Default valuecsv.Configuration.Comment ='#'; Byte count

To record how much Byte has been read, you need to set the Configuration.Encoding to be consistent with the CSV file. This setting affects the speed of parsing.

/ / Default valuecsv.Configuration.CountBytes = false;Culture information / / Default valuecsv.Configuration.CultureInfo = CultureInfo.CurrentCulture; separator / / Default valuecsv.Configuration.Delimiter = ","; the number of columns varies

If enabled, a CsvBadDataException will be thrown when the number of columns changes

/ / Default valuecsv.Configuration.DetectColumnCountChanges = false; encoding / / Default valuecsv.Configuration.Encoding = whether Encoding.UTF8; has a header record / / Default valuecsv.Configuration.HasHeaderRecord = true; ignores column name spaces

Whether to ignore spaces in column names

/ / Default valuecsv.Configuration.IgnoreHeaderWhiteSpace = false; ignores private access

Whether to ignore private accessors when reading and writing

/ / Default valuecsv.Configuration.IgnorePrivateAccessor = false; ignores read exception

Read continues after an exception occurs

/ / Default valuecsv.Configuration.IgnoreReadingExceptions = false; ignores quotation marks

Do not use quotation marks as escape characters

/ / Default valuecsv.Configuration.IgnoreQuotes = whether the false; column name is case-sensitive / / Default valuecsv.Configuration.IsHeaderCaseSensitive = true; mapping access

You can access custom class mappings

Var myMap = csv.Configuration.Maps [typeof (MyClass)]; attribute binding tag

Used to find properties of a custom class

/ / Default valuecsv.Configuration.PropertyBindingFlags = BindingFlags.Public | BindingFlags.Instance; text translated by tang yi ke jun Quote

Define escape characters that contain delimiters, parentheses, or the end of a line

/ / Default valuecsv.Configuration.Quote ='"'; all fields are in quotes

Whether to quote all fields when writing csv. QuoteAllFields and QuoteNoFields cannot be both true.

/ / Default valuecsv.Configuration.QuoteAllFields = false; all fields without quotation marks

QuoteAllFields and QuoteNoFields cannot be both true.

/ / Default valuecsv.Configuration.QuoteNoFields = callback of false; read exception csv.Configuration.ReadingExceptionCallback = (ex, row) = > {/ / Log the exception and current row information.}; register class mapping

If class mapping is used, registration is required before it is actually used.

Csv.Configuration.RegisterClassMap (); csv.Configuration.RegisterClassMap (); skip blank records

If all fields are empty, they are considered empty.

/ / Default valuecsv.Configuration.SkipEmptyRecords = false;Trim field

Delete the white space character at the end of the field.

/ / Default valuecsv.Configuration.TrimFields = false;Trim column name / / Default valuecsv.Configuration.TrimHeaders = false; unbind class mapping / / Unregister single map.csv.Configuration.UnregisterClassMap (); / / Unregister all class maps.csv.Configuration.UnregisterClassMap (); whether the empty field throws an exception / / Default valuecsv.Configuration.WillThrowOnMissingField = true; type conversion

Type conversion is CsvHelper's method of converting strings to .NET types (and vice versa).

Other view exception information Exception.Data ["CsvHelper"] / / Row:'3' (1 based) / / Type: 'CsvHelper.Tests.CsvReaderTests+TestBoolean'// Field Index:' 0' (0 based) / / Field Name: 'BoolColumn'// Field Value:' two'DataReader and DataTable

DataReader object is written to CSV

Var hasHeaderBeenWritten = false;while (dataReader.Read ()) {if (! hasHeaderBeenWritten) {for (var I = 0; I < dataReader.FieldCount; iTunes +) {csv.WriteField (dataReader.GetName (I))} csv.NextRecord (); hasHeaderBeenWritten = true;} for (var I = 0; I < dataReader.FieldCount; iTunes +) {csv.WriteField (dataReader [I]) } csv.NextRecord ();}

DataTable object is written to CSV

Using (var dt = new DataTable ()) {dt.Load (dataReader); foreach (DataColumn column in dt.Columns) {csv.WriteField (column.ColumnName);} csv.NextRecord (); foreach (DataRow row in dt.Rows) {for (var I = 0; I < dt.Columns.Count; iTunes +) {csv.WriteField (row [I]);} csv.NextRecord () }}

CSV to DataTable

While (csv.Read ()) {var row = dt.NewRow (); foreach (DataColumn column in dt.Columns) {row [column.ColumnName] = csv.GetField (column.DataType, column.ColumnName);} dt.Rows.Add (row) } Thank you for reading this article carefully. I hope the article "how to use CsvHelper" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report