Przejdź do treści stopki
KORZYSTANIE Z IRONXL

Jak zapisywać dane w pliku CSV w C#

This article will explore how to write a CSV file using IronXL.

Biblioteka IronXL

IronXL is a .NET Excel library that offers comprehensive functionality for creating, reading, and editing spreadsheet files in C# applications. It excels in terms of performance and output accuracy. It supports various spreadsheet workbook file formats such as XLS, XLSX, XLSM, CSV, and TSV. Additionally, it enables you to save or export data from Excel files to formats like CSV, JSON, HTML, Binary, Byte Array, DataSet, or DataTable.

With IronXL, developers can seamlessly work with worksheets and cell ranges, providing an elegant approach to manipulating data. It allows for easy editing of formulas and facilitates the recalculation of formulas within a sheet. Sorting data based on range, column, or row is straightforward. You can also modify layouts by freezing panes, auto-sizing rows/columns, and adding/removing rows/columns.

IronXL offers the ability to protect Excel files with user passwords and set permissions for editing. Furthermore, it provides features to add, remove, and extract images from Excel worksheets. The library includes a wide range of Excel functions, supporting various cell data formats. This makes IronXL one of the most intuitive APIs for working with Excel files.

A notable advantage of IronXL is that it does not require Microsoft Excel or Office Interop dependencies to be installed on the machine. It is a self-contained solution that works across multiple platforms and is compatible with .NET versions 7, 6, and 5. It also supports .NET Core 2 and 3, as well as the standard 2 version. For working with Excel spreadsheets, IronXL is compatible with .NET Framework 4.5 and later versions.

Create a Console Application

Visual Studio's latest version is recommended for creating an application to start with. Visual Studio is the official IDE for C# development, and you must have installed it. You can download it from the Microsoft Visual Studio website, if not installed.

The following steps will create a new project named "DemoApp".

  1. Open Visual Studio and click on "Create a New Project".

    How To Write Data in CSV File in C#, Figure 1: Open Visual Studio Open Visual Studio

  2. Select Console Application and click "Next".

    How To Write Data in CSV File in C#, Figure 2: Create a new project in Visual Studio Create a new project in Visual Studio

  3. Set the name of the project

    How To Write Data in CSV File in C#, Figure 3: Configure your new project Configure your new project

  4. Select the .NET version. Choose the stable version .NET 6.0.

    How To Write Data in CSV File in C#, Figure 4: .NET Framework selection .NET Framework selection

Install IronXL Library

Once the project is created, the IronXL library needs to be installed in the project to use it. Follow these steps to install it.

  1. Open NuGet Package Manager either from the Solution Explorer or tools.

    How To Write Data in CSV File in C#, Figure 5: Navigate to NuGet Package Manager Navigate to NuGet Package Manager

  2. Browse for IronXL Library and select the current project. Click install.

    How To Write Data in CSV File in C#, Figure 6: Search and install the IronXL package in NuGet Package Manager UI Wyszukaj i zainstaluj pakiet IronXL w interfejsie użytkownika NuGet Package Manager

Add the following namespace at the top of Program.cs file:

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

Create a New Workbook in C

IronXL provides the facility to create an empty workbook. A workbook is a spreadsheet which contains multiple worksheets. The data is stored in cells. CSV also looks like a spreadsheet but instead with a CSV file extension.

// Creates a new instance of WorkBook Spreadsheet
WorkBook workBook = WorkBook.Create();
// Creates a new instance of WorkBook Spreadsheet
WorkBook workBook = WorkBook.Create();
' Creates a new instance of WorkBook Spreadsheet
Dim workBook As WorkBook = WorkBook.Create()
$vbLabelText   $csharpLabel

Now, let's create a sheet in the WorkBook. There are multiple ways to create a worksheet in the workbook.

// Adds a default sheet to the workbook
WorkSheet defaultSheet = workBook.DefaultWorkSheet;

// Creates a worksheet with the name "Sheet1"
WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");
// Adds a default sheet to the workbook
WorkSheet defaultSheet = workBook.DefaultWorkSheet;

// Creates a worksheet with the name "Sheet1"
WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");
' Adds a default sheet to the workbook
Dim defaultSheet As WorkSheet = workBook.DefaultWorkSheet

' Creates a worksheet with the name "Sheet1"
Dim sheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")
$vbLabelText   $csharpLabel

If you want to add more sheets to your existing workbook, then use the CreateWorkSheet method.

Note: You can use WorkBook.LoadCSV method if the CSV file already exists. You can see this code example page for loading an existing CSV file.

Write Data to the WorkSheet

Writing CSV files is easy using IronXL. It provides Excel features to write data to CSVs. Cell references can be used to add the values at specified locations. Here, I'm going to add a few records of some employees using a foreach loop.

// Initialize an array of employee names
string[] employeeNames = { "John", "Peter", "Harry", "Kevin", "Brian" };

// Starting row for data entry
int i = 2;

// Setting header titles for the columns
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Salary";

// Populate each row with employee data
foreach (var employee in employeeNames)
{
    // Set values for ID, Name, and Salary
    sheet["A" + i].Value = i;
    sheet["B" + i].Value = employee;
    sheet["C" + i].Value = i * 1000;
    i++;
}
// Initialize an array of employee names
string[] employeeNames = { "John", "Peter", "Harry", "Kevin", "Brian" };

// Starting row for data entry
int i = 2;

// Setting header titles for the columns
sheet["A1"].Value = "ID";
sheet["B1"].Value = "Name";
sheet["C1"].Value = "Salary";

// Populate each row with employee data
foreach (var employee in employeeNames)
{
    // Set values for ID, Name, and Salary
    sheet["A" + i].Value = i;
    sheet["B" + i].Value = employee;
    sheet["C" + i].Value = i * 1000;
    i++;
}
' Initialize an array of employee names
Dim employeeNames() As String = { "John", "Peter", "Harry", "Kevin", "Brian" }

' Starting row for data entry
Dim i As Integer = 2

' Setting header titles for the columns
sheet("A1").Value = "ID"
sheet("B1").Value = "Name"
sheet("C1").Value = "Salary"

' Populate each row with employee data
For Each employee In employeeNames
	' Set values for ID, Name, and Salary
	sheet("A" & i).Value = i
	sheet("B" & i).Value = employee
	sheet("C" & i).Value = i * 1000
	i += 1
Next employee
$vbLabelText   $csharpLabel

In the above code example, an array of employeeNames is created, and the first row is set with headers: ID, Name, Salary. A variable i is also initialized with a value 2, which will enter the records from the 2nd row below the headers. The foreach loop processes each employee from the list and adds them to the current row with ID and salary values. Before the loop completes, i is incremented to move to the next row for the next record.

Save the Data to a CSV file

The last step is to save the CSV file. IronXL provides the method SaveAsCsv to save the workbook as a CSV file. The first parameter of this method is the CSV file name and the second is the delimiter.

// Save the modified workbook as a CSV file with a specified delimiter
workBook.SaveAsCsv("sample.csv", ",");
// Save the modified workbook as a CSV file with a specified delimiter
workBook.SaveAsCsv("sample.csv", ",");
' Save the modified workbook as a CSV file with a specified delimiter
workBook.SaveAsCsv("sample.csv", ",")
$vbLabelText   $csharpLabel

Pełny kod wygląda następująco:

using System;
using IronXL;

class Program
{
    static void Main()
    {
        // Create a new workbook and worksheet
        WorkBook workBook = WorkBook.Create();
        WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");

        // Initialize an array of employee names
        string[] employeeNames = { "John", "Peter", "Harry", "Kevin", "Brian" };

        // Starting row for data entry
        int i = 2;

        // Setting header titles for the columns
        sheet["A1"].Value = "ID";
        sheet["B1"].Value = "Name";
        sheet["C1"].Value = "Salary";

        // Populate each row with employee data
        foreach (var employee in employeeNames)
        {
            // Set values for ID, Name, and Salary
            sheet["A" + i].Value = i;
            sheet["B" + i].Value = employee;
            sheet["C" + i].Value = i * 1000;
            i++;
        }

        // Save the modified workbook as a CSV file with a specified delimiter
        workBook.SaveAsCsv("sample.csv", ",");
    }
}
using System;
using IronXL;

class Program
{
    static void Main()
    {
        // Create a new workbook and worksheet
        WorkBook workBook = WorkBook.Create();
        WorkSheet sheet = workBook.CreateWorkSheet("Sheet1");

        // Initialize an array of employee names
        string[] employeeNames = { "John", "Peter", "Harry", "Kevin", "Brian" };

        // Starting row for data entry
        int i = 2;

        // Setting header titles for the columns
        sheet["A1"].Value = "ID";
        sheet["B1"].Value = "Name";
        sheet["C1"].Value = "Salary";

        // Populate each row with employee data
        foreach (var employee in employeeNames)
        {
            // Set values for ID, Name, and Salary
            sheet["A" + i].Value = i;
            sheet["B" + i].Value = employee;
            sheet["C" + i].Value = i * 1000;
            i++;
        }

        // Save the modified workbook as a CSV file with a specified delimiter
        workBook.SaveAsCsv("sample.csv", ",");
    }
}
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main()
		' Create a new workbook and worksheet
		Dim workBook As WorkBook = WorkBook.Create()
		Dim sheet As WorkSheet = workBook.CreateWorkSheet("Sheet1")

		' Initialize an array of employee names
		Dim employeeNames() As String = { "John", "Peter", "Harry", "Kevin", "Brian" }

		' Starting row for data entry
		Dim i As Integer = 2

		' Setting header titles for the columns
		sheet("A1").Value = "ID"
		sheet("B1").Value = "Name"
		sheet("C1").Value = "Salary"

		' Populate each row with employee data
		For Each employee In employeeNames
			' Set values for ID, Name, and Salary
			sheet("A" & i).Value = i
			sheet("B" & i).Value = employee
			sheet("C" & i).Value = i * 1000
			i += 1
		Next employee

		' Save the modified workbook as a CSV file with a specified delimiter
		workBook.SaveAsCsv("sample.csv", ",")
	End Sub
End Class
$vbLabelText   $csharpLabel

Output

How To Write Data in CSV File in C#, Figure 7: The output CSV file Plik CSV wyjściowy

Podsumowanie

This article presents a simple approach to writing a CSV file using IronXL in C#. IronXL also provides the facility to work with existing CSV files without any hassle. It also allows you to write CSV files, create new Excel files, and write data to them with simple syntax. IronXL can also be used to read and write Excel files without Microsoft Office installed. For conversion between different spreadsheet formats, you can see this code example page.

IronXL jest bezpłatny do celów programistycznych, a na cele komercyjne można uzyskać licencję. You can also try the IronXL free trial for commercial use.

Często Zadawane Pytania

Jak mogę zapisać dane w pliku CSV w C#?

Możesz użyć metody `SaveAsCsv` z IronXL, aby wyeksportować dane do pliku CSV w C#. Najpierw utwórz skoroszyt i arkusz kalkulacyjny, zapisz dane do komórek, a następnie użyj `workBook.SaveAsCsv("filename.csv", ",");`, aby zapisać dane jako plik CSV.

Jakie są kroki tworzenia aplikacji konsolowej do zapisywania plików CSV w C#?

Aby stworzyć aplikację konsolową do zapisywania plików CSV, załóż nowy projekt w Visual Studio, wybierz odpowiednią wersję .NET i zainstaluj IronXL przez Menedżera pakietów NuGet. Następnie użyj IronXL, aby utworzyć skoroszyt, dodać dane do arkusza i zapisać je jako CSV.

Czy mogę zapisać dane w pliku CSV bez korzystania z Microsoft Excel?

Tak, możesz zapisać dane w pliku CSV bez korzystania z Microsoft Excel, używając IronXL. Umożliwia on programową manipulację plikami Excel i CSV bez konieczności instalacji Excela.

Jak zainstalować IronXL w projekcie Visual Studio?

Możesz zainstalować IronXL, otwierając Menedżera pakietów NuGet w Visual Studio, wyszukując 'IronXL' i klikając 'Install', aby dodać go do swojego projektu. To umożliwi korzystanie z funkcji IronXL do obsługi plików Excel i CSV.

Jakie formaty plików obsługuje IronXL do eksportu?

IronXL obsługuje eksport danych do kilku formatów, w tym CSV, JSON, HTML, Binary, Byte Array, DataSet i DataTable, dzięki czemu jest wszechstronnym narzędziem dostosowanym do różnych potrzeb związanych z obsługą danych.

Czy IronXL jest kompatybilny z różnymi wersjami .NET?

Tak, IronXL jest kompatybilny z wieloma wersjami .NET, w tym .NET Core 2 i 3, a także .NET 5, 6 i 7, co zapewnia programistom elastyczność w różnych środowiskach programistycznych.

Czy mogę używać IronXL w projektach komercyjnych?

Tak, IronXL może być licencjonowany do celów komercyjnych. Oferuje również bezpłatną wersję próbną do użytku deweloperskiego, umożliwiającą programistom przetestowanie jego funkcji przed zakupem licencji komercyjnej.

Jak utworzyć nowy skoroszyt i arkusz w języku C# przy użyciu IronXL?

Można utworzyć nowy skoroszyt i arkusz, używając `WorkBook.Create()` do zainicjowania obiektu skoroszytu, a następnie dodając do niego nowy arkusz. Umożliwia to rozpoczęcie zapisywania danych w arkuszu.

Czy IronXL wymaga jakichkolwiek zależności Office Interop?

Nie, biblioteka IronXL jest samodzielną biblioteką, która nie wymaga żadnych zależności Office Interop, co sprawia, że jest łatwa w użyciu i wdrażaniu w aplikacjach na różnych platformach.

Jordi Bardia
Inżynier oprogramowania
Jordi jest najbardziej biegły w Pythonie, C# i C++. Kiedy nie wykorzystuje swoich umiejętności w Iron Software, programuje gry. Dzieląc odpowiedzialność za testowanie produktów, rozwój produktów i badania, Jordi wnosi ogromną wartość do ciągłej poprawy produktów. Różnorodne doświadczenia ...
Czytaj więcej

Zespol wsparcia Iron

Jestesmy online 24 godziny, 5 dni w tygodniu.
Czat
Email
Zadzwon do mnie