跳至页脚内容
使用 IRONXL

如何在 C# 中使用 IronXL 将数据保存为 CSV

Managing CSV files is a fundamental requirement in modern C# applications, from generating business reports to exporting database records. While .NET provides basic file writing capabilities, handling CSV files efficiently, especially when dealing with special characters, multiple data types, and large datasets would require a more robust solution. IronXL simplifies this entire process by providing a comprehensive API that handles CSV operations, such as C# save to CSV, alongside full Excel compatibility.

This tutorial demonstrates how to leverage IronXL's powerful features for creating, saving, and managing CSV files in your C# applications. You'll learn practical techniques for handling various data sources, from simple collections to complex DataTables, all while maintaining clean and maintainable code.

How to Save Data to CSV in C# with IronXL: Image 1 - IronXL

Getting Started with IronXL

Before diving into CSV operations, you'll need to install IronXL in your project. The library supports .NET Framework 4.6.2+ and .NET Core 2+, making it compatible with both legacy and modern applications. IronXL also provides excellent cross-platform support, running seamlessly on Windows, Linux, and macOS environments.

How to Save Data to CSV in C# with IronXL: Image 2 - Cross Platform

Open Visual Studio, go to Package Manager Console and type the following command:

Install-Package IronXL.Excel

How to Save Data to CSV in C# with IronXL: Image 3 - Installation

Or via .NET CLI:

dotnet add package IronXL.Excel
dotnet add package IronXL.Excel
SHELL

Once installed, add the IronXL namespace to your C# file to access all the CSV management features, such as write data:

using IronXL;
using IronXL;
Imports IronXL
$vbLabelText   $csharpLabel

This simple setup gives you immediate access to powerful spreadsheet manipulation capabilities. Unlike traditional approaches that require Excel Interop or complex CSV parsing logic, IronXL provides an intuitive API that handles the complexities behind the scenes. The library operates independently without requiring Microsoft Office installation, making it ideal for server deployments and containerized applications.

If an error occurred while installing or initializing the library, ensure that your project targets a supported .NET version and that all dependencies are correctly restored.

How to Save and Write Data to New CSV Files?

Creating or writing CSV files from scratch with IronXL follows an intuitive pattern. You start by creating a workbook, add all the data to cells, and then save it in CSV format. This approach provides much more control than basic string concatenation methods.

Before diving into the main CSV creation logic, here’s a simple model definition using a public class student structure. This model represents structured data that we can later export to CSV.

// Define a Student class to model your data
public class Student
{
    public string? Name { get; set; } // public string firstname, public string lastname
    public int Age { get; set; }
    public string? Grade { get; set; }
}
// Define a Student class to model your data
public class Student
{
    public string? Name { get; set; } // public string firstname, public string lastname
    public int Age { get; set; }
    public string? Grade { get; set; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

You can populate a list of student objects and then use IronXL to export them efficiently to a CSV file. This example shows how to map class properties to worksheet cells:

using System;
using System.Collections.Generic;
using IronXL;
class Program
{
    static void Main(string[] args)
    {
        // Create sample data using the student class
        List<Student> students = new List<Student>()
        {
            new Student { Name = "Alice Johnson", Age = 20, Grade = "A" },
            new Student { Name = "Brian Smith", Age = 22, Grade = "B+" },
            new Student { Name = "Chloe Brown", Age = 19, Grade = "A-" },
            new Student { Name = "David Clark", Age = 21, Grade = "B" }
        };
        // Create a new workbook and worksheet
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet sheet = workbook.CreateWorkSheet("Students");
        // Add headers
        sheet["A1"].Value = "Name";
        sheet["B1"].Value = "Age";
        sheet["C1"].Value = "Grade";
        // Add student data to the worksheet
        for (int i = 0; i < students.Count; i++)
        {
            sheet[$"A{i + 2}"].Value = students[i].Name;
            sheet[$"B{i + 2}"].IntValue = students[i].Age;
            sheet[$"C{i + 2}"].Value = students[i].Grade;
        }
        // Save as CSV file
        workbook.SaveAsCsv("students.csv");
        Console.WriteLine("students.csv file has been created successfully!");
    }
}
using System;
using System.Collections.Generic;
using IronXL;
class Program
{
    static void Main(string[] args)
    {
        // Create sample data using the student class
        List<Student> students = new List<Student>()
        {
            new Student { Name = "Alice Johnson", Age = 20, Grade = "A" },
            new Student { Name = "Brian Smith", Age = 22, Grade = "B+" },
            new Student { Name = "Chloe Brown", Age = 19, Grade = "A-" },
            new Student { Name = "David Clark", Age = 21, Grade = "B" }
        };
        // Create a new workbook and worksheet
        WorkBook workbook = WorkBook.Create(ExcelFileFormat.XLSX);
        WorkSheet sheet = workbook.CreateWorkSheet("Students");
        // Add headers
        sheet["A1"].Value = "Name";
        sheet["B1"].Value = "Age";
        sheet["C1"].Value = "Grade";
        // Add student data to the worksheet
        for (int i = 0; i < students.Count; i++)
        {
            sheet[$"A{i + 2}"].Value = students[i].Name;
            sheet[$"B{i + 2}"].IntValue = students[i].Age;
            sheet[$"C{i + 2}"].Value = students[i].Grade;
        }
        // Save as CSV file
        workbook.SaveAsCsv("students.csv");
        Console.WriteLine("students.csv file has been created successfully!");
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Explanation:

  1. The public class student defines the schema for your data model.
  2. A list of student objects is created with sample data.
  3. IronXL’s WorkBook and WorkSheet APIs are used to create a structured spreadsheet in memory.
  4. Headers are added manually to ensure readability in the CSV output.
  5. The student data is written row by row to the worksheet.
  6. Finally, the data is saved as a CSV file using SaveAsCsv().

Output

How to Save Data to CSV in C# with IronXL: Figure 4 - Console Output

How to Save Data to CSV in C# with IronXL: Figure 5 - Excel Output

This pattern is scalable; as such you can easily adapt it for larger datasets or integrate it into an application that retrieves student data from a database or API.

For instance, if an error occurred while writing to the file (e.g., file locked or path invalid), you can handle it gracefully:

try
{
    workbook.SaveAsCsv("students.csv");
}
catch (Exception ex)
{
    Console.WriteLine($"Error occurred while saving CSV: {ex.Message}");
}
try
{
    workbook.SaveAsCsv("students.csv");
}
catch (Exception ex)
{
    Console.WriteLine($"Error occurred while saving CSV: {ex.Message}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This ensures your application remains robust and informative even when file I/O issues arise.

The following is the sample code to create a basic CSV file.

static void Main(string[] args)
{
 // Create a new workbook
 var writer = WorkBook.Create(ExcelFileFormat.XLSX);
 WorkSheet sheet = writer.CreateWorkSheet("Sales Data");
 // Add headers
 sheet["A1"].Value = "Product";
 sheet["B1"].Value = "Quantity";
 sheet["C1"].Value = "Price";
 sheet["D1"].Value = "Total";
 // Add data rows
 sheet["A2"].Value = "Widget A";
 sheet["B2"].IntValue = 100;
 sheet["C2"].DecimalValue = 29.99m;
 sheet["D2"].Formula = "=B2*C2";
 sheet["A3"].Value = "Widget B";
 sheet["B3"].IntValue = 50;
 sheet["C3"].DecimalValue = 49.99m;
 sheet["D3"].Formula = "=B3*C3";
 // Save as new CSV file
 writer.SaveAsCsv("sales_report.csv");
}
static void Main(string[] args)
{
 // Create a new workbook
 var writer = WorkBook.Create(ExcelFileFormat.XLSX);
 WorkSheet sheet = writer.CreateWorkSheet("Sales Data");
 // Add headers
 sheet["A1"].Value = "Product";
 sheet["B1"].Value = "Quantity";
 sheet["C1"].Value = "Price";
 sheet["D1"].Value = "Total";
 // Add data rows
 sheet["A2"].Value = "Widget A";
 sheet["B2"].IntValue = 100;
 sheet["C2"].DecimalValue = 29.99m;
 sheet["D2"].Formula = "=B2*C2";
 sheet["A3"].Value = "Widget B";
 sheet["B3"].IntValue = 50;
 sheet["C3"].DecimalValue = 49.99m;
 sheet["D3"].Formula = "=B3*C3";
 // Save as new CSV file
 writer.SaveAsCsv("sales_report.csv");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code creates a structured workbook with headers and data, then exports it to CSV format. The WorkBook.Create() method initializes a new spreadsheet in memory. Each cell can hold different data types, such as strings, integers, decimals, and even formulas. When you call SaveAsCsv(), IronXL automatically handles the conversion, properly escaping any special characters and maintaining data integrity.

The beauty of this approach lies in its flexibility. You can manipulate the data as a spreadsheet before exporting, applying formulas, formatting, or validation rules. IronXL evaluates formulas automatically during the export process, ensuring your CSV contains the calculated values rather than the formula text.

Output

How to Save Data to CSV in C# with IronXL: Figure 6 - CSV Output

For custom delimiter requirements, IronXL allows you to specify alternatives to the standard comma:

// Save with semicolon delimiter for European locale compatibility
workbook.SaveAsCsv("sales_report.csv", ";");
// Save with tab delimiter
workbook.SaveAsCsv("sales_report.tsv", "\t");
// Save with semicolon delimiter for European locale compatibility
workbook.SaveAsCsv("sales_report.csv", ";");
// Save with tab delimiter
workbook.SaveAsCsv("sales_report.tsv", "\t");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This flexibility ensures compatibility with various regional settings and application requirements. The library automatically handles encoding issues, ensuring proper character representation across different systems and locales.

How to Save Data to CSV in C# with IronXL: Figure 7 - Features

How to Export DataTable to CSV?

DataTables are ubiquitous in .NET applications for storing tabular data from databases or business logic. IronXL provides seamless DataTable to CSV conversion, preserving column names and data types throughout the process.

// Create a sample DataTable (simulating database results) to store data
DataTable customerOrders = new DataTable("CustomerOrders");
customerOrders.Columns.Add("OrderID", typeof(int));
customerOrders.Columns.Add("CustomerName", typeof(string));
customerOrders.Columns.Add("OrderDate", typeof(DateTime));
customerOrders.Columns.Add("Amount", typeof(decimal));
// Add sample data
customerOrders.Rows.Add(1001, "Acme Corp", new DateTime(2024, 1, 15), 1250.50m);
customerOrders.Rows.Add(1002, "TechStart Inc", new DateTime(2024, 1, 16), 3500.00m);
customerOrders.Rows.Add(1003, "Global Systems", new DateTime(2024, 1, 17), 875.25m);
// Convert DataTable to CSV using IronXL
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Orders");
// Add headers from DataTable columns
for (int i = 0; i < customerOrders.Columns.Count; i++)
{
    sheet.SetCellValue(0, i, customerOrders.Columns[i].ColumnName);
}
// Add data rows
for (int row = 0; row < customerOrders.Rows.Count; row++)
{
    for (int col = 0; col < customerOrders.Columns.Count; col++)
    {
        sheet.SetCellValue(row + 1, col, customerOrders.Rows[row][col]);
    }
}
// Export to CSV
workbook.SaveAsCsv("customer_orders.csv");
// Create a sample DataTable (simulating database results) to store data
DataTable customerOrders = new DataTable("CustomerOrders");
customerOrders.Columns.Add("OrderID", typeof(int));
customerOrders.Columns.Add("CustomerName", typeof(string));
customerOrders.Columns.Add("OrderDate", typeof(DateTime));
customerOrders.Columns.Add("Amount", typeof(decimal));
// Add sample data
customerOrders.Rows.Add(1001, "Acme Corp", new DateTime(2024, 1, 15), 1250.50m);
customerOrders.Rows.Add(1002, "TechStart Inc", new DateTime(2024, 1, 16), 3500.00m);
customerOrders.Rows.Add(1003, "Global Systems", new DateTime(2024, 1, 17), 875.25m);
// Convert DataTable to CSV using IronXL
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Orders");
// Add headers from DataTable columns
for (int i = 0; i < customerOrders.Columns.Count; i++)
{
    sheet.SetCellValue(0, i, customerOrders.Columns[i].ColumnName);
}
// Add data rows
for (int row = 0; row < customerOrders.Rows.Count; row++)
{
    for (int col = 0; col < customerOrders.Columns.Count; col++)
    {
        sheet.SetCellValue(row + 1, col, customerOrders.Rows[row][col]);
    }
}
// Export to CSV
workbook.SaveAsCsv("customer_orders.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This example demonstrates a real-world scenario where order data from a database needs to be exported for reporting or integration purposes. The code iterates through the DataTable structure, preserving column headers and row data. IronXL handles the conversion of different data types appropriately, ensuring dates, decimals, and strings are properly formatted in the resulting CSV file.

Output

How to Save Data to CSV in C# with IronXL: Figure 8 - DataTable to CSV Output

For more complex scenarios involving multiple related tables or advanced data transformations, you can leverage IronXL's cell referencing and formula capabilities:

// Add summary row with formulas
int lastRow = customerOrders.Rows.Count + 1;
sheet[$"A{lastRow + 1}"].Value = "Total:";
sheet[$"D{lastRow + 1}"].Formula = $"=SUM(D2:D{lastRow})";
// Calculate and save
workbook.SaveAsCsv("customer_orders_with_total.csv");
// Add summary row with formulas
int lastRow = customerOrders.Rows.Count + 1;
sheet[$"A{lastRow + 1}"].Value = "Total:";
sheet[$"D{lastRow + 1}"].Formula = $"=SUM(D2:D{lastRow})";
// Calculate and save
workbook.SaveAsCsv("customer_orders_with_total.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This approach provides much more control than traditional DataTable export methods. You can add calculated fields, apply conditional formatting logic, or reorganize columns before the final export. The IronXL documentation provides comprehensive examples for advanced DataTable manipulation scenarios.

How to Convert Excel Files to CSV?

One of IronXL's strongest features is its ability to work seamlessly with existing Excel files, converting them to CSV format while preserving data integrity. This is particularly useful when integrating with systems that produce Excel reports but require CSV for downstream processing.

// Load an existing Excel file
WorkBook existingWorkbook = WorkBook.Load("Budget.xlsx");
// Access the first worksheet
WorkSheet sheet = existingWorkbook.WorkSheets[0];
// Save as CSV - single sheet
sheet.SaveAsCsv("Budget.csv");
// Or save entire workbook (creates multiple CSV files for multiple sheets)
existingWorkbook.SaveAsCsv("BudgetReport.csv");
// Load an existing Excel file
WorkBook existingWorkbook = WorkBook.Load("Budget.xlsx");
// Access the first worksheet
WorkSheet sheet = existingWorkbook.WorkSheets[0];
// Save as CSV - single sheet
sheet.SaveAsCsv("Budget.csv");
// Or save entire workbook (creates multiple CSV files for multiple sheets)
existingWorkbook.SaveAsCsv("BudgetReport.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

When loading Excel files, IronXL preserves all cell values, including those calculated by formulas. The library evaluates Excel formulas during the conversion process, ensuring your CSV contains the actual calculated values. This eliminates the common problem of formula text appearing in CSV exports.

Input

How to Save Data to CSV in C# with IronXL: Figure 9 - Sample Input

Output

How to Save Data to CSV in C# with IronXL: Figure 10 - Excel to CSV Output

For workbooks containing multiple sheets, IronXL handles each sheet intelligently:

// Process multiple sheets
WorkBook multiSheetWorkbook = WorkBook.Load("annual_data.xlsx");
foreach (WorkSheet sheet in multiSheetWorkbook.WorkSheets)
{
    string fileName = $"export_{sheet.Name}.csv";
    sheet.SaveAsCsv(fileName);
    Console.WriteLine($"Exported {sheet.Name} to {fileName}");
}
// Process multiple sheets
WorkBook multiSheetWorkbook = WorkBook.Load("annual_data.xlsx");
foreach (WorkSheet sheet in multiSheetWorkbook.WorkSheets)
{
    string fileName = $"export_{sheet.Name}.csv";
    sheet.SaveAsCsv(fileName);
    Console.WriteLine($"Exported {sheet.Name} to {fileName}");
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

This code iterates through all worksheets in an Excel file, creating separate CSV files for each sheet. The sheet names are preserved in the file naming, making it easy to identify the source of each CSV file. IronXL supports various Excel formats, including XLSX, XLS, XLSM, and XLTX, providing broad compatibility with different Excel versions and use cases. Learn more about converting between formats in the documentation.

Advanced CSV Management Techniques

Beyond basic CSV creation, IronXL offers sophisticated features for handling complex scenarios that often arise in production environments. These capabilities set it apart from simple file writing approaches.

When dealing with special characters, IronXL automatically handles escaping and encoding:

WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
// Data with special characters
sheet["A1"].Value = "Company \"ABC\", Inc.";  // Quotes
sheet["B1"].Value = "Line 1\nLine 2";         // Newlines
sheet["C1"].Value = "Price: €50,00";          // Unicode characters
workbook.SaveAsCsv("special_chars.csv");
WorkBook workbook = WorkBook.Create();
WorkSheet sheet = workbook.CreateWorkSheet("Data");
// Data with special characters
sheet["A1"].Value = "Company \"ABC\", Inc.";  // Quotes
sheet["B1"].Value = "Line 1\nLine 2";         // Newlines
sheet["C1"].Value = "Price: €50,00";          // Unicode characters
workbook.SaveAsCsv("special_chars.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

IronXL properly escapes quotes, handles multi-line content, and preserves Unicode characters. This automatic handling prevents common CSV parsing errors that occur with manual string manipulation approaches.

Output

How to Save Data to CSV in C# with IronXL: Figure 11 - Special Characters Output

For batch processing scenarios, you can efficiently handle multiple files:

string[] sourceFiles = Directory.GetFiles("input_folder", "*.xlsx");
foreach (string file in sourceFiles)
{
    WorkBook wb = WorkBook.Load(file);
    var csv = Path.ChangeExtension(file, ".csv");
    wb.SaveAsCsv(csv);
}
string[] sourceFiles = Directory.GetFiles("input_folder", "*.xlsx");
foreach (string file in sourceFiles)
{
    WorkBook wb = WorkBook.Load(file);
    var csv = Path.ChangeExtension(file, ".csv");
    wb.SaveAsCsv(csv);
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Memory efficiency becomes crucial when processing large datasets. IronXL optimizes memory usage internally, but you can further improve performance by processing data in chunks and properly disposing of resources:

WorkBook largeWorkbook = WorkBook.Create();
WorkSheet sheet = largeWorkbook.CreateWorkSheet("LargeData");
// Process in batches
const int batchSize = 1000;
for (int batch = 0; batch < 10; batch++)
{
 for (int row = 0; row < batchSize; row++)
 {
  int actualRow = (batch * batchSize) + row;
  sheet.SetCellValue(actualRow, 0, $"Row {actualRow}");
  // Add more data...
  sheet.SetCellValue(actualRow, 1, DateTime.Now);
  sheet.SetCellValue(actualRow, 2, $"Batch {batch + 1}");
 }
}
largeWorkbook.SaveAsCsv("large_dataset.csv");
WorkBook largeWorkbook = WorkBook.Create();
WorkSheet sheet = largeWorkbook.CreateWorkSheet("LargeData");
// Process in batches
const int batchSize = 1000;
for (int batch = 0; batch < 10; batch++)
{
 for (int row = 0; row < batchSize; row++)
 {
  int actualRow = (batch * batchSize) + row;
  sheet.SetCellValue(actualRow, 0, $"Row {actualRow}");
  // Add more data...
  sheet.SetCellValue(actualRow, 1, DateTime.Now);
  sheet.SetCellValue(actualRow, 2, $"Batch {batch + 1}");
 }
}
largeWorkbook.SaveAsCsv("large_dataset.csv");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output

How to Save Data to CSV in C# with IronXL: Figure 12 - Large Dataset Output

Conclusion

IronXL transforms CSV file management in C# from a tedious task into a straightforward process. By providing a unified API for both CSV and Excel operations, it eliminates the need for multiple libraries or complex parsing logic. The library's automatic handling of special characters, data types, and encoding issues ensures reliable data export across different systems and locales.

Whether you're building reporting systems, data integration pipelines, or simple export features, IronXL provides the tools needed for efficient CSV management. Its compatibility with existing Excel files and DataTable structures makes it easy to integrate into existing applications without major refactoring. Once your CSV files are generated, you can open them directly in Excel or inspect their raw format using any text editor for quick validation or troubleshooting.

Ready to streamline your CSV operations? Start with a free trial and includes professional support and updates.

How to Save Data to CSV in C# with IronXL: Figure 13 - Licensing

常见问题解答

使用IronXL在C#中保存数据为CSV的优势是什么?

IronXL提供了简化处理CSV操作的全面API,包括将数据保存为CSV,同时还提供完整的Excel兼容性,使其更易于管理特殊字符、多种数据类型和大数据集。

IronXL如何处理CSV文件中的特殊字符?

IronXL通过提供强大的解析和写入能力,有效管理CSV文件中的特殊字符,确保在文件操作期间维护数据完整性。

IronXL在保存为CSV时能否管理大型数据集?

是的,IronXL专为高效处理大型数据集而设计,提供性能优化的方法,将数据保存到CSV文件中而不影响速度或可靠性。

IronXL是否支持CSV操作的多种数据类型?

IronXL支持多种数据类型,使开发者能够无缝地将复杂的数据集导出为CSV格式,而不会遇到数据类型兼容性问题。

在处理CSV文件时,IronXL与Excel兼容吗?

IronXL提供完整的Excel兼容性,这意味着它可以在处理CSV文件时与Excel操作一起使用,使其成为处理电子表格数据的开发者的多功能工具。

是什么让IronXL成为C#中CSV文件管理的强大解决方案?

IronXL的强大解决方案来自其全面的API,该API简化了复杂的CSV操作,并提供了Excel兼容性和对大型数据集的支持等附加功能。

IronXL如何简化在C#中保存为CSV的过程?

IronXL通过抽象与CSV文件管理相关的复杂性简化了过程,为开发者提供了简便的方法以高效地将数据保存为CSV。

Curtis Chau
技术作家

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

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