CsvHelper is a .NET library for reading and writing CSV files. CsvHelper can be downloaded through Visual Studio's package manager. Automatic mapping definition: When no mapping file is provided, the default is automatic mapping, and automatic mapping will be mapped to the attributes of the class in order.
GitHub address
var csv = new CsvReader( textReader ); var records = csv.GetRecords(); // 把 CSV 记录映射到 MyClass,返回的 records 是个 IEnumerable 对象
If you want to customize the mapping relationship, you can see the mapping section below.
Since records is an IEnumerable
var csv = new CsvReader( textReader ); var records = csv.GetRecords().ToList();
You can read the data of each row in a row loop
var csv = new CsvReader( textReader ); while( csv.Read() ) { var record = csv.GetRecord(); }
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 read type may be different from 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. } }
If you want each line to be returned as a string, you can use CsvParser .
var parser = new CsvParser( textReader ); while( true ) { var row = parser.Read(); // row 是个字符串 if( row == null ) { break; } }
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(); }
If no mapping file is provided, the default For automatic mapping, automatic mapping will be mapped to the attributes of the class in order. If the attribute is a custom class, it will continue to be filled in according to the attributes of this custom class. If a circular reference occurs, automatic mapping stops.
If the CSV file and the custom class do not exactly match, 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 translated by tangyikejun
If the attribute is a custom class that corresponds to multiple columns of 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 ); } }
You can specify mapping by column subscript
public sealed class MyClassMap : CsvClassMap{ public MyClassMap() { Map( m => m.Id ).Index( 0 ); Map( m => m.Name ).Index( 1 ); } }
You can also specify mapping by column name, which requires csv The file has a header record, which means that the first line records the column name
public sealed class MyClassMap : CsvClassMap{ public MyClassMap() { Map( m => m.Id ).Name( "The Id Column" ); Map( m => m.Name ).Name( "The Name Column" ); } }
public sealed class MyClassMap : CsvClassMap{ public MyClassMap() { Map( m => m.FirstName ).Name( "Name" ).NameIndex( 0 ); Map( m => m.LastName ).Name( "Name" ).NameIndex( 1 ); } }
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" ); } }
public sealed class MyClassMap : CsvClassMap{ public MyClassMap() { Map( m => m.Id ).Index( 0 ).TypeConverter (); } }
The default converter will handle most type conversions, but sometimes we may need to make some small changes. At this time, we can try to use optional type conversion.
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 ); // 时间格式转换 Map( m => m.Cost ).Index( 2 ).TypeConverterOption( NumberStyles.Currency ); // 数值类型转换 Map( m => m.CurrencyFormat ).Index( 3 ).TypeConverterOption( "C" ); Map( m => m.BooleanValue ).Index( 4 ).TypeConverterOption( true, "sure" ).TypeConverterOption( false, "nope" ); // 内容转换 } }
public sealed class MyClassMap : CsvClassMap{ public MyClassMap() { // 常数 Map( m => m.Constant ).ConvertUsing( row => 3 ); // 把两列聚合在一起 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. } ); } }
Mappings can be created at runtime.
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);
This article was translated by tangyikejun
// Default value csv.Configuration.AllowComments = false;
var generatedMap = csv.Configuration.AutoMap();
TextReader Or the cache of reading and writing in TextWriter
// Default value csv.Configuration.BufferSize = 2048;
The commented out line will not be loaded in
// Default value csv.Configuration.Comment = '#';
Record the current read How many bytes have been retrieved? Configuration.Encoding needs to be set to be consistent with the CSV file. This setting will affect the speed of parsing.
// Default value csv.Configuration.CountBytes = false;
// Default value csv.Configuration.CultureInfo = CultureInfo.CurrentCulture;
// Default value csv.Configuration.Delimiter = ",";
If turned on, a CsvBadDataException will be thrown if the column number changes
// Default value csv.Configuration.DetectColumnCountChanges = false;
// Default value csv.Configuration.Encoding = Encoding.UTF8;
// Default value csv.Configuration.HasHeaderRecord = true;
Whether spaces in column names are ignored
// Default value csv.Configuration.IgnoreHeaderWhiteSpace = false;
Whether to ignore private accessors when reading and writing
// Default value csv.Configuration.IgnorePrivateAccessor = false;
Continue reading after an exception occurs during reading
// Default value csv.Configuration.IgnoreReadingExceptions = false;
Do not use quotes as escape characters
// Default value csv.Configuration.IgnoreQuotes = false;
// Default value csv.Configuration.IsHeaderCaseSensitive = true;
You can access custom class mappings
var myMap = csv.Configuration.Maps[typeof( MyClass )];
Used to find attributes of custom classes
// Default value csv.Configuration.PropertyBindingFlags = BindingFlags.Public | BindingFlags.Instance;
This article was translated by tang yi ke jun
Define the escape character used to escape delimiters, brackets or line endings
// Default value csv.Configuration.Quote = '"';
Whether to quote all fields when writing to csv. QuoteAllFields and QuoteNoFields cannot be true at the same time.
// Default value csv.Configuration.QuoteAllFields = false;
QuoteAllFields and QuoteNoFields cannot be true at the same time.
// Default value csv.Configuration.QuoteNoFields = false;
csv.Configuration.ReadingExceptionCallback = ( ex, row ) => { // Log the exception and current row information. };
If class mapping is used, it needs to be registered before it will be actually used.
csv.Configuration.RegisterClassMap(); csv.Configuration.RegisterClassMap ();
If all fields are empty, they will be considered empty fields
// Default value csv.Configuration.SkipEmptyRecords = false;
Put the field content Trailing whitespace characters are deleted.
// Default value csv.Configuration.TrimFields = false;
// Default value csv.Configuration.TrimHeaders = false;
// Unregister single map. csv.Configuration.UnregisterClassMap(); // Unregister all class maps. csv.Configuration.UnregisterClassMap();
// Default value csv.Configuration.WillThrowOnMissingField = true;
Type Conversions are CsvHelper's way of converting strings to .NET types (and vice versa).
Exception.Data["CsvHelper"] // Row: '3' (1 based) // Type: 'CsvHelper.Tests.CsvReaderTests+TestBoolean' // Field Index: '0' (0 based) // Field Name: 'BoolColumn' // Field Value: 'two'
DataReader object is written to CSV
var hasHeaderBeenWritten = false; while( dataReader.Read() ) { if( !hasHeaderBeenWritten ) { for( var i = 0; i < dataReader.FieldCount; i++ ) { csv.WriteField( dataReader.GetName( i ) ); } csv.NextRecord(); hasHeaderBeenWritten = true; } for( var i = 0; i < dataReader.FieldCount; i++ ) { 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; i++ ) { 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 ); }
Related articles:
jQuery EasyUI API Chinese Documentation - Documentation Documentation_jquery
Related videos:
The above is the detailed content of A .NET library for technical solutions to CSV files: CsvHelper Chinese documentation. For more information, please follow other related articles on the PHP Chinese website!