跳至页脚内容
与其他组件比较

IronXL 和 CsvWriter 的比较

Working with CSV files can be a challenging task. However, today there are many libraries available to help developers with this task, and without the need to have Microsoft Excel installed.

In this article, we are going to discuss and compare how to work with Microsoft Excel documents programmatically in C# .NET technologies, either in CSV format or the standard Excel format, using two of the most popular libraries, IronXL and CSVWriter.

Let's look firstly at what both libraries have to offer.

The IronXL Library

IronXL is a .NET library that facilitates the reading and editing of Microsoft Excel documents with C#. IronXL.Excel is a standalone .NET software library for reading a wide range of spreadsheet formats. It does not requireMicrosoft Excelto be installed, nor does it depend on Interop.

IronXL is an intuitive C# APIthat allows you to read, edit, and create Excel spreadsheet files in .NET with lightning-fast performance. IronXL fully supports .NET Core, .NET Framework, Xamarin, Mobile, Linux, macOS, and Azure.

IronXL is a leading .NET core and .net framework Excel spreadsheet library for C#.

IronXL Feature Set

  • Load, read, and edit data — from XLS/XLSX/CSV/TSV
  • Saving and exporting — to XLS/XLSX/CSV/TSV/JSON
  • Ranges — easy to use WorkSheet ["A1:B10"] syntax. Combine and create ranges intuitively.
  • Sorting — sort ranges, columns, and rows.
  • Styling — cell visual styles, font, size, background pattern, border, alignment, and number formats.

CSVWriter

A .NET library for writing CSV files. Extremely fast, flexible, and easy to use. Supports writing custom class objects.

CsvWriter Features

  • Fast: compiles classes on the fly for extremely fast performance
  • Flexible: conservative when writing, liberal when reading
  • Easy to use: reading and writing are as simple as GetRecords<T>() and WriteRecords(records)
  • Highly configurable
  • Linux mode
  • Low memory usage

1. Create a Console Application

Use the following steps to create a Console Application:

  • Start the Visual Studio 2022 IDE.
  • Click on “Create new project”.
  • In the “Create new project” page, selectC#in the language drop-down list,Windowsfrom thePlatformslist, andConsolefrom the “Project types” list.
  • SelectConsole App (.NET Framework)from the project templates displayed.
Csvhelper Alternatives 1 related to 1. Create a Console Application

Create Project - Console Application

  • ClickNext.
  • In theAdditional Informationscreen, specify theFramework versionyou would like to use. We will use.NET Framework 4.8in this example.
Csvhelper Alternatives 2 related to 1. Create a Console Application

Create Project - .NET Framework

  • ClickCreateto complete the process.

The project is now created and we are almost ready to test the libraries. However, we still need to install and integrate them into our project. Let's install IronXL first.

2. IronXL C# Library Installation

You can download and install the IronXL library using the following methods:

  1. Using Visual Studio with NuGet packages
  2. Download the NuGet Package directly
  3. Manually Install with the DLL

Let’s take a closer look at each one.

2.1. Using Visual Studio with NuGet packages

Visual Studio provides the NuGet Package Manager to install NuGet packages in your projects. You can access it through the Project Menu, or by right-clicking your project in the Solution Explorer.

Csvhelper Alternatives 3 related to 2.1. Using Visual Studio with NuGet packages

Select-Manage-NuGet-Package

  • Now, from the browse tab -> search for IronXL.Excel -> Install
Csvhelper Alternatives 4 related to 2.1. Using Visual Studio with NuGet packages

Search for IronXL

  • And we are done.

2.2. Download the NuGet Package Directly

This can be done by visiting the NuGet site directly and downloading the package. The steps are:

2.3. Manually Install with the DLL

Another way to download and install the IronXL C# Library is to make use of the following steps to install theIronXLNuGet packagethrough the Developer Command Prompt.

  • Openthe Developer Command Prompt— usually found in the Visual Studio folder.
  • Type the following command:
    Install-Package IronXL.Excel
  • Press Enter
  • This will download and install the package
  • Reload your Visual Studio project and begin using it

2.4. Add Necessary Using Directives

  1. InSolution Explorer, right-click theProgram.csfile and then clickView Code.
  2. Add the followingusingdirectives to the top of the code file:
using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

All done! IronXL is downloaded, installed, and ready to use. However, before that, we should install CsvHelper.

3. CSVWriter Installation

3.1. Using the NuGet Package Manager Console

To work with CSVWriter you need to download and install the CsvHelper C# Library. To do so, make use of the following steps to install theNuGet packagethrough the Developer Command Prompt.

  • Openthe Developer Command Prompt— usually found in the Visual Studio folder.
  • Type the following command:
    Install-Package CsvHelper -Version 27.2.1
  • Press Enter
  • This will download and install the package
  • Reload your Visual Studio project and begin using it
  • Check the CsvHelper.CsvWriter method detail for implementation

3.2. Direct Download

Download from the NuGet website: https://www.nuget.org/packages/CsvHelper/

4. Working with CSV Files using IronXL

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. To manipulate these files for calculations can be a challenging task, but IronXL provides a pretty good and easy option to achieve this, and without using Microsoft Excel. Let's first convert a CSV file to a normal Excel file.

4.1. Converting a CSV File to Excel Format

The process is pretty simple and easy. It is usually done with one line of code.

CSV to Excel formats:

// Load the CSV file and specify the format and delimiter
WorkBook workbook = WorkBook.LoadCSV("test.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
// Get the default worksheet
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook as an Excel file
workbook.SaveAs("CsvToExcelConversion.xlsx");
// Load the CSV file and specify the format and delimiter
WorkBook workbook = WorkBook.LoadCSV("test.csv", fileFormat: ExcelFileFormat.XLSX, ListDelimiter: ",");
// Get the default worksheet
WorkSheet ws = workbook.DefaultWorkSheet;

// Save the workbook as an Excel file
workbook.SaveAs("CsvToExcelConversion.xlsx");
' Load the CSV file and specify the format and delimiter
Dim workbook As WorkBook = WorkBook.LoadCSV("test.csv", fileFormat:= ExcelFileFormat.XLSX, ListDelimiter:= ",")
' Get the default worksheet
Dim ws As WorkSheet = workbook.DefaultWorkSheet

' Save the workbook as an Excel file
workbook.SaveAs("CsvToExcelConversion.xlsx")
$vbLabelText   $csharpLabel

4.2. Read and Manipulate Converted CSV Files using IronXL

The IronXLWorkBookclass represents an Excel sheet. To open an Excel File using C#, we use WorkBook.Load and specify the path of the Excel file (.xlsx). The following one-line code is used to open the file for reading:

// Load WorkBook
var workbook = WorkBook.Load(@"Spreadsheets\\sample.xlsx");
// Load WorkBook
var workbook = WorkBook.Load(@"Spreadsheets\\sample.xlsx");
' Load WorkBook
Dim workbook = WorkBook.Load("Spreadsheets\\sample.xlsx")
$vbLabelText   $csharpLabel

Each WorkBook can contain multipleWorkSheetobjects. These represent worksheets in the Excel document. If the workbook contains worksheets, retrieve them by name as follows:

// Open Sheet for reading
var worksheet = workbook.GetWorkSheet("sheetnamegoeshere");
// Open Sheet for reading
var worksheet = workbook.GetWorkSheet("sheetnamegoeshere");
' Open Sheet for reading
Dim worksheet = workbook.GetWorkSheet("sheetnamegoeshere")
$vbLabelText   $csharpLabel

Code for reading the cell values:

// Read from Ranges of cells elegantly.
foreach (var cell in worksheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
// Read from Ranges of cells elegantly.
foreach (var cell in worksheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
' Read from Ranges of cells elegantly.
For Each cell In worksheet("A2:A10")
	Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
$vbLabelText   $csharpLabel

After loading and reading the workbook and worksheet, the following code sample can be used to either make changes to formulas or apply formulas to specific cells. The code goes as follows:

// Set Formulas
worksheet["A1"].Formula = "Sum(B8:C12)";
worksheet["B8"].Formula = "=C9/C11";
worksheet["G30"].Formula = "Max(C3:C7)";

// Force recalculate all formula values in all sheets.  
workbook.EvaluateAll();
// Set Formulas
worksheet["A1"].Formula = "Sum(B8:C12)";
worksheet["B8"].Formula = "=C9/C11";
worksheet["G30"].Formula = "Max(C3:C7)";

// Force recalculate all formula values in all sheets.  
workbook.EvaluateAll();
' Set Formulas
worksheet("A1").Formula = "Sum(B8:C12)"
worksheet("B8").Formula = "=C9/C11"
worksheet("G30").Formula = "Max(C3:C7)"

' Force recalculate all formula values in all sheets.  
workbook.EvaluateAll()
$vbLabelText   $csharpLabel

4.3. Saving the Excel document back to CSV File

Writing CSV files is an easy process with IronXL. The following code simply saves the Excel file in the CSV format by using the SaveAsCsv method.

// Load the workbook
WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx");
// Save as .csv file
wb.SaveAsCsv("SaveAsCSV.csv", ",");
// Saved as : SaveAsCSV.Sheet1.csv
// Load the workbook
WorkBook wb = WorkBook.Load("Normal_Excel_File.xlsx");
// Save as .csv file
wb.SaveAsCsv("SaveAsCSV.csv", ",");
// Saved as : SaveAsCSV.Sheet1.csv
' Load the workbook
Dim wb As WorkBook = WorkBook.Load("Normal_Excel_File.xlsx")
' Save as .csv file
wb.SaveAsCsv("SaveAsCSV.csv", ",")
' Saved as : SaveAsCSV.Sheet1.csv
$vbLabelText   $csharpLabel

5. Working with CSV Data using CSVWriter

Writing data to a CSV file is a common operation. CSVHelper method CSVWriter with supplied separator handles all the characters and new line characters in a very simple CSV writer released for C#. Here we are going to look at how to write data using CSVWriter.

5.1. Create a Simple Console Application

Create a simple CSVWriter with supplied separator console application using Visual Studio. Once the project is created, the next step is to create a Person class:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsLiving { get; set; }
}
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool IsLiving { get; set; }
}
Public Class Person
	Public Property Id() As Integer
	Public Property Name() As String
	Public Property IsLiving() As Boolean
End Class
$vbLabelText   $csharpLabel

Within the Main method, let’s now make a list of Person objects which we will write to the CSV file:

var myPersonObjects = new List<Person>()
{
    new Person { Id = 1, IsLiving = true, Name = "John" },
    new Person { Id = 2, IsLiving = true, Name = "Steve" },
    new Person { Id = 3, IsLiving = true, Name = "James" }
};
var myPersonObjects = new List<Person>()
{
    new Person { Id = 1, IsLiving = true, Name = "John" },
    new Person { Id = 2, IsLiving = true, Name = "Steve" },
    new Person { Id = 3, IsLiving = true, Name = "James" }
};
Dim myPersonObjects = New List(Of Person)() From {
	New Person With {
		.Id = 1,
		.IsLiving = True,
		.Name = "John"
	},
	New Person With {
		.Id = 2,
		.IsLiving = True,
		.Name = "Steve"
	},
	New Person With {
		.Id = 3,
		.IsLiving = True,
		.Name = "James"
	}
}
$vbLabelText   $csharpLabel

5.2. Writing into a CSV File in C# with Default Settings

CsvHelper has emerged as the standard way to write CSV in C# using the CSVWriter method, and it is very easy to use:

using (var writer = new StreamWriter("filePersons.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(myPersonObjects);
}
using (var writer = new StreamWriter("filePersons.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(myPersonObjects);
}
Using writer = New StreamWriter("filePersons.csv")
Using csv = New CsvWriter(writer, CultureInfo.InvariantCulture)
	csv.WriteRecords(myPersonObjects)
End Using
End Using
$vbLabelText   $csharpLabel

5.3. Appending Data

We need to keep in mind the fact that every time we run our program, old CSV files will be overwritten. Sometimes we want the data to be appended at the end of a file, instead of overwriting existing data. CSVWriter doesn’t provide a method to do this, as opening/writing a file is not the responsibility of CSVWriter with supplied separator. We can achieve this by using a FileStream, and then constructing our StreamWriter by using that FileStream. Although this does not fall within the scope of this article, I will show you how to do it, as it is an integral part of any application.

var configPersons = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    HasHeaderRecord = false
};
using (var stream = File.Open("filePersons.csv", FileMode.Append))
using (var writer = new StreamWriter(stream))
using (var csv = new CsvWriter(writer, configPersons))
{
    csv.WriteRecords(myPersonObjects);
}
var configPersons = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    HasHeaderRecord = false
};
using (var stream = File.Open("filePersons.csv", FileMode.Append))
using (var writer = new StreamWriter(stream))
using (var csv = new CsvWriter(writer, configPersons))
{
    csv.WriteRecords(myPersonObjects);
}
Dim configPersons = New CsvConfiguration(CultureInfo.InvariantCulture) With {.HasHeaderRecord = False}
Using stream = File.Open("filePersons.csv", FileMode.Append)
Using writer = New StreamWriter(stream)
Using csv = New CsvWriter(writer, configPersons)
	csv.WriteRecords(myPersonObjects)
End Using
End Using
End Using
$vbLabelText   $csharpLabel

Appending to an existing file is tricky, however, as the ordering might be changed when we append, or we might have added new properties. We should make sure to take this into account when appending.

6. Licensing

IronXL is an openly commercial C# Excel library. It is free for development and can always be licensed for commercial deployment.Licenses are availablefor single-project use, single developers, agencies, and global corporations, as well as SaaS and OEM redistribution. All licenses include a 30-day money-back guarantee, one year of product support and updates, validity for dev/staging/production, and also a permanent license (one-time purchase). The Lite package starts from $799.

CSVWriter with supplied separator is a comma-separated element and completely free for commercial-friendly use.

7. Summary and Conclusion

Summary

IronXL is a complete library offering everything you need to be able to manipulate an Excel file. It provides you the facility to convert various formats to XLSX, and also from XLSX to other formats, such as CSV. This interconversion provides users the flexibility to manipulate other file formats with ease.

On the other hand, CSVWriter works only with CSV file formats and with very limited options. Users cannot switch between different file formats, whereas with IronXL they can. All the code samples can be found in the CsvHelper documentation files. This document provides guidelines on how to use CSVWriter in your project.

Conclusion

IronXL has a clear advantage over CSVHelper.CSVWriter, as it supports working with multiple formats. Moreover, you can apply formulas and styles according to your choice, whereas CsvHelper only allows for the reading and writing of CSV files, and with limited options. Further, you cannot append new records to an existing CSV file, as it simply overwrites previous entries.

常见问题解答

处理 C# 中 Excel 文档的 CSVWriter 换代方案有哪些?

IronXL 是处理 C# 中 Excel 文档的 CSVWriter 的绝佳替代方案。 它可以让您读取、编辑和导出各种 Excel 格式,如 XLS、XLSX、CSV 和 TSV,而不需要 Microsoft Excel。

如何使用 .NET 库将 CSV 文件转换为 Excel 格式?

使用 IronXL,您可以通过将 CSV 加载到工作簿中,然后将其保存为 XLSX 文件,轻松将 CSV 文件转换为 Excel 格式。 此过程涉及简单的代码命令来操作和保存文件。

IronXL 相对 CSVWriter 有哪些优势?

IronXL 相比 CSVWriter 提供了几个优势,包括支持多种文件格式、应用 Excel 公式的能力,以及数据排序和样式等高级功能。相比之下,CSVWriter 仅限于处理 CSV 文件。

如何在我的 C# 项目中安装 IronXL?

您可以通过 Visual Studio 中的 NuGet 包管理器在您的 C# 项目中安装 IronXL。或者,您可以下载 NuGet 包或通过开发者命令提示符手动安装 DLL。

IronXL 可以在 .NET Core 和 Azure 环境中使用吗?

是的,IronXL 支持多个平台,包括 .NET Core 和 Azure,使其成为在各种环境中需要 Excel 文件操作的应用程序开发的多功能选择。

用 CSVWriter 可以将自定义类对象写入到 CSV 文件中吗?

是的,CSVWriter 支持将自定义类对象写入到 CSV 文件中。它提供了一种灵活且易于使用的方法,可以在处理 CSV 文件时高效写入数据。

在商业应用中使用 IronXL 的许可证要求是什么?

IronXL 在商业用途中需要许可证。它对于开发目的是免费的,但根据部署需求(无论是单个项目还是企业级应用)有不同类型的许可证提供。

IronXL 如何处理 Excel 公式?

IronXL 允许您在电子表格中应用和操作 Excel 公式,为在您的 C# 应用程序中进行动态数据计算和分析提供了强大的功能。

使用 IronXL 时一些常见的故障排除问题是什么?

IronXL 的常见故障排除问题可能包括文件格式兼容性、数据类型不匹配或安装错误。确保您的项目引用设置正确并验证数据格式可以帮助解决这些问题。

IronXL 可以向现有 Excel 文件追加数据吗?

是的,IronXL 可以向现有 Excel 文件追加数据。它允许您打开一个现有的工作簿,通过添加新数据进行修改,然后保存更改而不会覆盖现有内容。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。