跳至页脚内容
使用 IRONXL

如何在 C# 中写入 CSV 文件

This article will introduce how to write CSV files using a C# library named IronXL in a new project.

How to Write a CSV File

  1. Install the C# library for writing into a CSV File.

  2. Use WorkBook.Create to create a new workbook.

  3. Create a new worksheet using WorkBook.CreateWorkSheet.

  4. Add values to individual cells using workSheet["cell name"].Value using var.

  5. Save the spreadsheet as a CSV file using the SaveAs method.

IronXL

IronXL emerges as a beacon of efficiency for C# developers seeking a seamless and powerful solution for writing data to CSV files as compared to the CSVHelper NuGet package. In the dynamic landscape of software development, the ability to handle and manipulate data is paramount, and IronXL steps up to the plate with its robust set of tools tailored for C#.

This article delves into the features and methodologies that make IronXL the go-to choice for C# developers looking to enhance the process of writing data to CSV files, striking the perfect balance between simplicity and precision.

Create a New Visual Studio Project

To begin using the IronXL library, the initial step involves either creating a fresh Visual Studio C# project or loading an existing one. Here are the instructions for generating a new project in Visual Studio:

  1. Open Visual Studio and navigate to the "File" menu. A drop-down menu will be displayed; within this menu, select "New". This action will reveal another side menu.

    How to Write A CSV File in C#, Figure 1: File Menu File Menu

  2. In the side menu, locate and click on "Project". This will open a new window. Within this window, utilize the search bar to find "Console Application". Choose the option associated with C# and proceed by clicking the Next button.

    How to Write A CSV File in C#, Figure 2: New Project- Console Application New Project- Console Application

  3. A configuration window will appear next. Enter the project name, specify the project location, and click on the Next button.

    How to Write A CSV File in C#, Figure 3: Configure Project Configure Project

  4. The final window will emerge. Here, pick the target framework and initiate the project creation process by clicking on the Create button.

    How to Write A CSV File in C#, Figure 4: Target Framework Target Framework

Installing CSV Library IronXL

Now that you've set up the project, it's time to incorporate the IronXL C# library. Follow these steps to install IronXL in your project:

  1. In Visual Studio, navigate to the Tools menu. A dropdown menu will emerge—select the NuGet Package Manager from this menu.
  2. Within the NuGet Package Manager, choose the Manage NuGet Packages for Solutions from the side menu that unfolds.

    How to Write A CSV File in C#, Figure 5: NuGet Packages NuGet Packages

  3. A new window will pop up. Head to the browser tab within this window, and in the search bar, type "IronXL". You'll see a list of IronXL packages; opt for the latest one and proceed to click on the Install button.

    How to Write A CSV File in C#, Figure 6: IronXL IronXL

Writing CSV Files Using IronXL

Write data into a CSV file using the C# CSV library IronXL. In this section, we will create a new CSV file and write data in it. The following example uses the IronXL library to create a simple receipt in a CSV file. Let's break down the program code step by step.

Importing IronXL and System.Linq

using IronXL; 
using System.Linq;

// This is the main class where execution starts.
public class Program {
    static void Main() {
        // Main method where all logic is executed
    }
}
using IronXL; 
using System.Linq;

// This is the main class where execution starts.
public class Program {
    static void Main() {
        // Main method where all logic is executed
    }
}
Imports IronXL
Imports System.Linq

' This is the main class where execution starts.
Public Class Program
	Shared Sub Main()
		' Main method where all logic is executed
	End Sub
End Class
$vbLabelText   $csharpLabel

These lines import the necessary classes and functionalities from the IronXL library for working with Excel files and the LINQ extension methods from the System.Linq namespace.

Creating a WorkBook and WorkSheet

// Create a new workbook. This serves as the container for all worksheets.
WorkBook workBook = WorkBook.Create();

// Create a new worksheet within the workbook named "Receipt".
WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");
// Create a new workbook. This serves as the container for all worksheets.
WorkBook workBook = WorkBook.Create();

// Create a new worksheet within the workbook named "Receipt".
WorkSheet workSheet = workBook.CreateWorkSheet("Receipt");
' Create a new workbook. This serves as the container for all worksheets.
Dim workBook As WorkBook = WorkBook.Create()

' Create a new worksheet within the workbook named "Receipt".
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Receipt")
$vbLabelText   $csharpLabel

This code creates a new Excel workbook (WorkBook) and a worksheet (WorkSheet) within that workbook named "Receipt".

Adding Headers

// Set the header row for columns. Headers added for better understanding of data.
workSheet["A1"].Value = "Product"; 
workSheet["B1"].Value = "Price";
// Set the header row for columns. Headers added for better understanding of data.
workSheet["A1"].Value = "Product"; 
workSheet["B1"].Value = "Price";
' Set the header row for columns. Headers added for better understanding of data.
workSheet("A1").Value = "Product"
workSheet("B1").Value = "Price"
$vbLabelText   $csharpLabel

These lines set the header row for the columns in the first row of the worksheet, labeling each column.

Populating Item Information

// Populate worksheet with product data and their respective prices.
workSheet["A2"].Value = "Item 1"; 
workSheet["B2"].DoubleValue = 20.10; 

workSheet["A3"].Value = "Item 2"; 
workSheet["B3"].DoubleValue = 15.50; 

workSheet["A4"].Value = "Item 3"; 
workSheet["B4"].DoubleValue = 10.25;
// Populate worksheet with product data and their respective prices.
workSheet["A2"].Value = "Item 1"; 
workSheet["B2"].DoubleValue = 20.10; 

workSheet["A3"].Value = "Item 2"; 
workSheet["B3"].DoubleValue = 15.50; 

workSheet["A4"].Value = "Item 3"; 
workSheet["B4"].DoubleValue = 10.25;
' Populate worksheet with product data and their respective prices.
workSheet("A2").Value = "Item 1"
workSheet("B2").DoubleValue = 20.10

workSheet("A3").Value = "Item 2"
workSheet("B3").DoubleValue = 15.50

workSheet("A4").Value = "Item 3"
workSheet("B4").DoubleValue = 10.25
$vbLabelText   $csharpLabel

These lines add information about three items, including their names and prices in the worksheet.

Calculating Total Price

// Define the range for price values to be summed.
var range = workSheet["B2:B4"];

// Calculate the sum of prices.
decimal sum = range.Sum();
// Define the range for price values to be summed.
var range = workSheet["B2:B4"];

// Calculate the sum of prices.
decimal sum = range.Sum();
' Define the range for price values to be summed.
Dim range = workSheet("B2:B4")

' Calculate the sum of prices.
Dim sum As Decimal = range.Sum()
$vbLabelText   $csharpLabel

Using LINQ, this code calculates the sum of the prices from cells B2 to B4. The sum is stored in the sum variable.

Displaying and Updating Total in the WorkSheet

// Display the sum in the console.
System.Console.WriteLine(sum);

// Update the total price in the worksheet.
workSheet["B5"].Value = sum;
// Display the sum in the console.
System.Console.WriteLine(sum);

// Update the total price in the worksheet.
workSheet["B5"].Value = sum;
' Display the sum in the console.
System.Console.WriteLine(sum)

' Update the total price in the worksheet.
workSheet("B5").Value = sum
$vbLabelText   $csharpLabel

The sum is printed to the console, and it is also updated in cell B5 of the worksheet.

Saving the Workbook as a CSV File

// Save the workbook as a CSV file named "receipt.csv".
workBook.SaveAs("receipt.csv");
// Save the workbook as a CSV file named "receipt.csv".
workBook.SaveAs("receipt.csv");
' Save the workbook as a CSV file named "receipt.csv".
workBook.SaveAs("receipt.csv")
$vbLabelText   $csharpLabel

Finally, the entire workbook is saved as a CSV file named "receipt.csv".

In summary, this code creates a basic receipt in an Excel worksheet using IronXL, calculates the total price, prints it to the console, and then saves the workbook output as a CSV file. The receipt includes columns for "Product" and "Price", and it calculates the total price based on the individual item prices.

How to Write A CSV File in C#, Figure 7: Receipt CSV File Output with Header Receipt CSV File Output with Header

Conclusion

This comprehensive article underscores the significance of writing CSV files in C# and elucidates the process using the IronXL library. It emphasizes the fundamental nature of this skill in diverse data-centric applications and showcases IronXL's prowess in simplifying and optimizing data manipulation tasks within the C# ecosystem. The step-by-step approach, from project setup to utilizing IronXL to create a receipt and save it as a CSV file, provides developers with a practical understanding of the seamless integration between C#.

By offering versatility and efficiency, IronXL emerges as a valuable tool for C# developers seeking to enhance their program and ability to handle and export data in the ubiquitous CSV format, making it a crucial asset for various software development scenarios.

IronXL provides a solution for all Excel-related tasks to be done programmatically whether it be formula calculation, string sorting, trimming, finding and replacing, merging and unmerging, saving files etc. You can also set cell data formats.

For the complete tutorial on writing into a CSV file, visit this blog here. The code example for creating a CSV file can be found in the following blog.

IronXL offers a free trial, allowing you to evaluate its capabilities. If you find it useful for your projects, you can purchase a license starting from $799.

常见问题解答

如何在 C# 中编写 CSV 文件而无需使用 Interop?

您可以利用 IronXL 库在 C# 中编写 CSV 文件而无需 Interop 支持。IronXL 允许您创建工作簿和工作表、添加数据,并使用其内置方法直接将其保存为 CSV 文件。

与 CSVHelper 相比,IronXL 在编写 CSV 文件方面有哪些优势?

IronXL 提供了更广泛的功能,不仅限于 CSV 编写,例如公式计算、单元格格式和多种 Excel 格式的导出,为开发人员提供了更全面的解决方案。

如何在 C# 项目中开始使用 IronXL?

要开始使用 IronXL,您需要通过 Visual Studio 中的 NuGet 包管理器安装它。创建一个新的 C# 项目,导航到“工具”,选择“NuGet 包管理器”,搜索“IronXL”并安装。

除了编写 CSV,IronXL 可以用于操作 Excel 文件吗?

是的,IronXL 能够处理多种 Excel 相关任务,例如读取和写入 Excel 文件、执行公式计算以及管理多个工作表中的数据。

如何在 C# 中使用 IronXL 向工作表添加数据?

要使用 IronXL 向工作表添加数据,请使用其标识符访问单个单元格,并使用 Value 属性分配值。然后,您可以按照所需格式保存工作表。

如何使用 IronXL 将工作簿保存为 CSV 文件?

在 IronXL 中创建并填充您的工作簿和工作表后,您可以使用 SaveAs 方法将其保存为 CSV 文件,并指定文件路径和格式。

IronXL 是否提供可供评估的试用版本?

是的,IronXL 提供免费试用版,允许开发人员在购买前探索和评估其功能。

如何使用 IronXL 计算工作表中的数字总计?

您可以使用 IronXL 利用 LINQ 计算工作表中的一系列单元格的总计,利用该库与 C# 的 LINQ 表达式的兼容性。

在使用 IronXL 编写 CSV 文件时,有哪些常见问题?

常见问题可能包括文件路径或权限不正确、数据格式不匹配或数据字段丢失。正确的错误处理和验证可以帮助减轻这些问题。

IronXL 能够高效处理 C# 项目中的大数据集吗?

是的,IronXL 被设计为能够高效地处理大数据集,允许开发人员读取、编写和操作大 Excel 文件而不会显著性能滞后。

Curtis Chau
技术作家

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

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