search
HomeBackend DevelopmentC#.Net TutorialA .NET library for technical solutions to CSV files: CsvHelper Chinese documentation

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

Read

Read all records

var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>(); // 把 CSV 记录映射到 MyClass,返回的 records 是个 IEnumerable<T> 对象

If you want to customize the mapping relationship, you can see the mapping section below.
Since records is an IEnumerable object, a record will be returned only when accessed, and a record will be returned once accessed. If you want to access it like a list, you can do the following:

var csv = new CsvReader( textReader );
var records = csv.GetRecords<MyClass>().ToList();

Manually read records

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

var csv = new CsvReader( textReader );
while( csv.Read() )
{
    var record = csv.GetRecord<MyClass>();
}

Read individually The 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 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&#39;t convert.
    }
}

parse

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;
    }
}

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

Automatic mapping

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.

Manual Mapping

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<MyClass>
{
    public MyClassMap()
    {
        Map( m => m.Id );
        Map( m = > m.Name );
    }
}
This article is translated by tangyikejun

Reference mapping

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<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 );
    }
}

Subscript specification

You can specify mapping 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 specification

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<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 conversion

public sealed class MyClassMap : CsvClassMap<MyClass>
{
    public MyClassMap()
    {
        Map( m => m.Id ).Index( 0 ).TypeConverter<MyIdConverter>();
    }
}

can Optional type conversion

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<MyClass>
{
    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" ); // 内容转换
    }
}

ConvertUsing

public sealed class MyClassMap : CsvClassMap<MyClass>
{
    public MyClassMap()
    {
        // 常数
        Map( m => m.Constant ).ConvertUsing( row => 3 );
        // 把两列聚合在一起
        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.
        } );
    }
}

Runtime Mapping

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

Configuration

Allow comments

// Default value
csv.Configuration.AllowComments = false;

Automapping

var generatedMap = csv.Configuration.AutoMap<MyClass>();

Cache

TextReader Or the cache of reading and writing in TextWriter

// Default value
csv.Configuration.BufferSize = 2048;

Comment

The commented out line will not be loaded in

// Default value
csv.Configuration.Comment = &#39;#&#39;;

Byte count

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;

Culture information

// Default value
csv.Configuration.CultureInfo = CultureInfo.CurrentCulture;

Separator

// Default value
csv.Configuration.Delimiter = ",";

Column number change

If turned on, a CsvBadDataException will be thrown if the column number changes

// Default value
csv.Configuration.DetectColumnCountChanges = false;

Encoding

// Default value
csv.Configuration.Encoding = Encoding.UTF8;

Whether there is a header record

// Default value
csv.Configuration.HasHeaderRecord = true;

Ignore spaces in column names

Whether spaces in column names are ignored

// Default value
csv.Configuration.IgnoreHeaderWhiteSpace = false;

Ignore private access

Whether to ignore private accessors when reading and writing

// Default value
csv.Configuration.IgnorePrivateAccessor = false;

Ignore read exceptions

Continue reading after an exception occurs during reading

// Default value
csv.Configuration.IgnoreReadingExceptions = false;

Ignore quotation marks

Do not use quotes as escape characters

// Default value
csv.Configuration.IgnoreQuotes = false;

Whether column names are case-sensitive

// Default value
csv.Configuration.IsHeaderCaseSensitive = true;

Map access

You can access custom class mappings

var myMap = csv.Configuration.Maps[typeof( MyClass )];

Attribute binding tag

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

Quote

Define the escape character used to escape delimiters, brackets or line endings

// Default value
csv.Configuration.Quote = &#39;"&#39;;

Quotation marks for all fields

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;

All fields are not quoted

QuoteAllFields and QuoteNoFields cannot be true at the same time.

// Default value
csv.Configuration.QuoteNoFields = false;

Read exception callback

csv.Configuration.ReadingExceptionCallback = ( ex, row ) =>
{
    // Log the exception and current row information.
};

Register class mapping

If class mapping is used, it needs to be registered before it will be actually used.

csv.Configuration.RegisterClassMap<MyClassMap>();
csv.Configuration.RegisterClassMap<AnotherClassMap>();

Skip blank records

If all fields are empty, they will be considered empty fields

// Default value
csv.Configuration.SkipEmptyRecords = false;

Trim fields

Put the field content Trailing whitespace characters are deleted.

// Default value
csv.Configuration.TrimFields = false;

Trim column name

// Default value
csv.Configuration.TrimHeaders = false;

Unbinding class mapping

// Unregister single map.
csv.Configuration.UnregisterClassMap<MyClassMap>();
// Unregister all class maps.
csv.Configuration.UnregisterClassMap();

Whether an empty field throws an exception

// Default value
csv.Configuration.WillThrowOnMissingField = true;

Type conversion

Type Conversions are CsvHelper's way of converting strings to .NET types (and vice versa).

Others

View exception information

Exception.Data["CsvHelper"]

// Row: &#39;3&#39; (1 based)
// Type: &#39;CsvHelper.Tests.CsvReaderTests+TestBoolean&#39;
// Field Index: &#39;0&#39; (0 based)
// Field Name: &#39;BoolColumn&#39;
// Field Value: &#39;two&#39;

DataReader and DataTable

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:

.net CsvHelper 2.0

jQuery EasyUI API Chinese Documentation - Documentation Documentation_jquery

Related videos:

Ruby Chinese Documentation

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!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
C# .NET for Web, Desktop, and Mobile DevelopmentC# .NET for Web, Desktop, and Mobile DevelopmentApr 25, 2025 am 12:01 AM

C# and .NET are suitable for web, desktop and mobile development. 1) In web development, ASP.NETCore supports cross-platform development. 2) Desktop development uses WPF and WinForms, which are suitable for different needs. 3) Mobile development realizes cross-platform applications through Xamarin.

C# .NET Ecosystem: Frameworks, Libraries, and ToolsC# .NET Ecosystem: Frameworks, Libraries, and ToolsApr 24, 2025 am 12:02 AM

The C#.NET ecosystem provides rich frameworks and libraries to help developers build applications efficiently. 1.ASP.NETCore is used to build high-performance web applications, 2.EntityFrameworkCore is used for database operations. By understanding the use and best practices of these tools, developers can improve the quality and performance of their applications.

Deploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideDeploying C# .NET Applications to Azure/AWS: A Step-by-Step GuideApr 23, 2025 am 12:06 AM

How to deploy a C# .NET app to Azure or AWS? The answer is to use AzureAppService and AWSElasticBeanstalk. 1. On Azure, automate deployment using AzureAppService and AzurePipelines. 2. On AWS, use Amazon ElasticBeanstalk and AWSLambda to implement deployment and serverless compute.

C# .NET: An Introduction to the Powerful Programming LanguageC# .NET: An Introduction to the Powerful Programming LanguageApr 22, 2025 am 12:04 AM

The combination of C# and .NET provides developers with a powerful programming environment. 1) C# supports polymorphism and asynchronous programming, 2) .NET provides cross-platform capabilities and concurrent processing mechanisms, which makes them widely used in desktop, web and mobile application development.

.NET Framework vs. C#: Decoding the Terminology.NET Framework vs. C#: Decoding the TerminologyApr 21, 2025 am 12:05 AM

.NETFramework is a software framework, and C# is a programming language. 1..NETFramework provides libraries and services, supporting desktop, web and mobile application development. 2.C# is designed for .NETFramework and supports modern programming functions. 3..NETFramework manages code execution through CLR, and the C# code is compiled into IL and runs by CLR. 4. Use .NETFramework to quickly develop applications, and C# provides advanced functions such as LINQ. 5. Common errors include type conversion and asynchronous programming deadlocks. VisualStudio tools are required for debugging.

Demystifying C# .NET: An Overview for BeginnersDemystifying C# .NET: An Overview for BeginnersApr 20, 2025 am 12:11 AM

C# is a modern, object-oriented programming language developed by Microsoft, and .NET is a development framework provided by Microsoft. C# combines the performance of C and the simplicity of Java, and is suitable for building various applications. The .NET framework supports multiple languages, provides garbage collection mechanisms, and simplifies memory management.

C# and the .NET Runtime: How They Work TogetherC# and the .NET Runtime: How They Work TogetherApr 19, 2025 am 12:04 AM

C# and .NET runtime work closely together to empower developers to efficient, powerful and cross-platform development capabilities. 1) C# is a type-safe and object-oriented programming language designed to integrate seamlessly with the .NET framework. 2) The .NET runtime manages the execution of C# code, provides garbage collection, type safety and other services, and ensures efficient and cross-platform operation.

C# .NET Development: A Beginner's Guide to Getting StartedC# .NET Development: A Beginner's Guide to Getting StartedApr 18, 2025 am 12:17 AM

To start C#.NET development, you need to: 1. Understand the basic knowledge of C# and the core concepts of the .NET framework; 2. Master the basic concepts of variables, data types, control structures, functions and classes; 3. Learn advanced features of C#, such as LINQ and asynchronous programming; 4. Be familiar with debugging techniques and performance optimization methods for common errors. With these steps, you can gradually penetrate the world of C#.NET and write efficient applications.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools