Csvhelper is a. NET library that reads and writes a CSV file. Csvhelper can be downloaded through the Package manager of Visual Studio. Automatic mapping definition: In the absence of a mapping file, the default is auto-mapping, and the automatic mapping is sequentially mapped to the properties of the class.
GitHub Address
Read
Read all the records
Var csv = new CsvReader( textReader );
Var records = csv.GetRecords<MyClass>(); // Map the CSV record to MyClass and the returned records are an IEnumerable<T> object
If you want to customize the mapping relationship, you can look at the following mapping section.
Because records is a Ienumerable<t> object, only one record is returned when accessed, and a record is returned once. If you want to access the list like this, you can do the following:
var csv = new Csvreader (TextReader); var records = csv. Getrecords<myclass> (). ToList ();
Manually Read records
You can iterate through each row of data by row
var csv = new CsvReader( textReader );
while( csv.Read() )
{
var record = csv.GetRecord<MyClass>();
}
Read a separate field
var csv = new CsvReader( textReader );
while( csv.Read() )
{
var intField = csv.GetField<int>( 0 );
var stringField = csv.GetField<string>( 1 );
var boolField = csv.GetField<bool>( "HeaderName" );
}
If the type of reading may be different from what is expected, you can use the Trygetfield
var csv = new CsvReader( textReader );
while( csv.Read() )
{
int intField;
if( !csv.TryGetField( 0, out intField ) )
{
// Do something when it can't convert.
}
}
Analytical
You can use Csvparser to return each line as a string.
var parser = new CsvParser( textReader );
while( true )
{
var row = parser.Read(); //Row is a string
if( row == null )
{
break;
}
}
Write
Write 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
Auto Map
If the mapping file is not provided, the default is auto-mapping, and the automatic mapping is sequentially mapped to the properties of the class. If the property is a custom class, it will continue to be populated with the properties of the custom class in turn. If a circular reference occurs, the automatic mapping stops.
Manual mapping
If the CSV file and the custom class are not fully matched, you can define a matching class to handle.
public sealed class MyClassMap : CsvClassMap<MyClass>
{
public MyClassMap()
{
Map( m => m.Id );
Map( m = > m.Name );
}
}
This article is translated by Tangyikejun
Reference mappings
If the property is a custom class that corresponds to multiple columns in a CSV file, you can use reference mappings.
public sealed class PersonMap : CsvClassMap<Person>
{
public PersonMap()
{
Map( m => m.Id );
Map( m => m.Name );
References<AddressMap>( m => m.Address );
}
}
public sealed class AddressMap : CsvClassMap<Address>
{
public AddressMap()
{
Map( m => m.Street );
Map( m => m.City );
Map( m => m.State );
Map( m => m.Zip );
}
}
The subscript specifies
Mapping can be specified by column subscript
public sealed class MyClassMap : CsvClassMap<MyClass>
{
public MyClassMap()
{
Map( m => m.Id ).Index( 0 );
Map( m => m.Name ).Index( 1 );
}
}
Column name Specifies
You can also specify a mapping by column name, which requires a CSV file to have a header record, which means that the first row records the column name
public sealed class MyClassMap : CsvClassMap<MyClass>
{
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<MyClass>
{
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<MyClass>
{
public override void MyClassMap()
{
Map( m => m.Id ).Index( 0 ).Default( -1 );
Map( m => m.Name ).Index( 1 ).Default( "Unknown" );
}
}
Type conversions
public sealed class MyClassMap : CsvClassMap<MyClass>
{
public MyClassMap()
{
Map( m => m.Id ).Index( 0 ).TypeConverter<MyIdConverter>();
}
}
Optional type conversions
The default converter handles most of the type conversions, but sometimes we may need to make some minor changes, and at this point we can try to convert with an optional type.
Public sealed class MyClassMap : CsvClassMap<MyClass>
{
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
}
}
Convertusing
Public sealed class MyClassMap : CsvClassMap<MyClass>
{
Public MyClassMap()
{
// constant
Map( m => m.Constant ).ConvertUsing( row => 3 );
// Put the two columns together
Map( m => m.Aggregate ).ConvertUsing( row => row.GetField<int>( 0 ) + row.GetField<int>( 1 ) );
// Collection with a single value.
Map( m => m.Names ).ConvertUsing( row => new List<string>{ row.GetField<string>( "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.
} );
}
}
Run-time mappings
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);
This article is translated by Tangyikejun
Configuration
Allow annotations
Default Valuecsv. Configuration.allowcomments = false;
Auto Map
var generatedmap = csv. Configuration.automap<myclass> ();
Cache
Read-write cache in TextReader or TextWriter
Default Valuecsv. Configuration.buffersize = 2048;
Comments
The line that is commented out will not be loaded in.
Default valuecsv.Configuration.Comment = ' # ';
Byte Count
Record how many bytes are currently read, and you need to set the configuration.encoding to be the same as 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 = ",";
Number of columns changes
If turned on, the number of column changes will be thrown csvbaddataexception
Default Valuecsv. Configuration.detectcolumncountchanges = false;
Coding
Default Valuecsv. configuration.encoding = Encoding.UTF8;
Do you have a header record?
Default Valuecsv. Configuration.hasheaderrecord = true;
Ignore Column name spaces
Whether to ignore spaces in column names
Default Valuecsv. Configuration.ignoreheaderwhitespace = false;
Ignore private access
Ignore private accessors when reading and writing
Default Valuecsv. Configuration.ignoreprivateaccessor = false;
Ignore Read exception
Read after an exception continues reading
Default Valuecsv. Configuration.ignorereadingexceptions = false;
Ignore quotation marks
Do not use quotation marks as escape characters
Default Valuecsv. Configuration.ignorequotes = false;
Column names are case sensitive
Default Valuecsv. Configuration.isheadercasesensitive = true;
Map Access
Access to custom class mappings
var myMap = csv. Configuration.maps[typeof (MyClass)];
Property binding Tag
The properties used to find the custom class
Default Valuecsv. Configuration.propertybindingflags = BindingFlags.Public | BindingFlags.Instance;
This paper is translated by Tang Yi Ke June
Quote
Defines an escape character that is used to escape a containing delimiter, parenthesis, or end of line
Default Valuecsv. Configuration.quote = ' "';
All fields quoted
Whether to enclose all fields in quotation marks when writing to CSV. Quoteallfields and Quotenofields cannot be true at the same time.
Default Valuecsv. Configuration.quoteallfields = false;
All fields are unquoted
Quoteallfields and Quotenofields cannot be true at the same time.
Default Valuecsv. Configuration.quotenofields = false;
Callback to read exception
Csv. Configuration.readingexceptioncallback = (ex, row) =>{ //Log the exception and current row information.};
Registering Class Mappings
If you use a class-map, you need to register before it is actually used.
Csv. Configuration.registerclassmap<myclassmap> (); CSV. Configuration.registerclassmap<anotherclassmap> ();
Skip a blank record
If all fields are empty, they are considered null fields
Default Valuecsv. Configuration.skipemptyrecords = false;
Trim Field
Delete the blank character that the field is ending in.
Default Valuecsv. Configuration.trimfields = false;
Trim Column Name
Default Valuecsv. Configuration.trimheaders = false;
Unbind class Mappings
Unregister single map.csv.configuration.unregisterclassmap<myclassmap> ();
//Unregister All Class Maps.csv.Configuration.UnregisterClassMap ();
Whether an empty field throws an exception
Default Valuecsv. Configuration.willthrowonmissingfield = true;
Type conversions
Type conversions are methods that csvhelper convert strings to. NET types (and vice versa).
Other
Viewing 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 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 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:
. NET Csvhelper 2.0
JQuery Easyui API Chinese Document-documentation document _jquery
Related videos:
Ruby Chinese documentation