跳過到頁腳內容
使用 IRONXL

如何在 C# 中撰寫 CSV 文件中的數據

本文將探討如何使用 IronXL 撰寫 CSV 檔案。

IronXL 圖書館

IronXL是一個 .NET Excel 庫,它為在 C# 應用程式中建立、讀取和編輯電子表格檔案提供了全面的功能。 它的性能和輸出精度都非常出色。 它支援多種電子表格工作簿文件模式,例如 XLS、XLSX、XLSM、CSV 和 TSV。此外,它還允許您將 Excel 檔案中的資料儲存或匯出為 CSV、JSON、HTML、二進位、位元組數組、資料集或資料表等格式。

借助 IronXL,開發人員可以無縫地處理工作表和單元格區域,從而為資料操作提供了一種優雅的方法。 它允許輕鬆編輯公式,並方便在工作表中重新計算公式。 按範圍、列或行對資料進行排序非常簡單。 您也可以透過凍結窗格自動調整行/列大小以及新增/刪除行/列來修改版面配置。

IronXL 提供使用使用者密碼保護 Excel 檔案並設定編輯權限的功能。 此外,它還提供了在 Excel 工作表中新增、刪除和擷取影像的功能。 該程式庫包含各種 Excel 函數,支援多種儲存格資料格式。 這使得 IronXL 成為處理 Excel 檔案最直觀的 API 之一。

IronXL 的一個顯著優勢在於它無需在電腦上安裝 Microsoft Excel 或 Office Interop 依賴項。它是一個獨立的解決方案,可跨多個平台運行,並與 .NET 7、6 和 5 版本相容。此外,它還支援 .NET Core 2 和 3 以及標準的 .NET 2 版本。 IronXL 與 .NET Framework 4.5 及更高版本相容,可用於處理 Excel 電子表格。

建立控制台應用程式

建議使用最新版本的 Visual Studio 來建立應用程式。 Visual Studio 是 C# 開發的官方 IDE,您必須安裝它。 如果尚未安裝,您可以從Microsoft Visual Studio 網站下載。

以下步驟將建立一個名為"DemoApp"的新專案。

1.開啟 Visual Studio 並按一下"建立新專案"。

[如何在 C# 中將資料寫入 CSV 文件,圖 1:開啟 Visual Studio](/static-assets/excel/blog/how-to-write-data-in-csv-file-in-csharp-tutorial/how-to-write-data-in-csv-file-in-csharp-tutorial-1.webp)
**開啟 Visual Studio**
  1. 選擇控制台應用程序,然後按一下"下一步"。

    如何在 C# 中將資料寫入 CSV 文件,圖 2:在 Visual Studio 中建立一個新項目 在 Visual Studio 中建立一個新項目

  2. 設定項目名稱

    如何在 C# 中將資料寫入 CSV 文件,圖 3:配置新項目 配置您的新項目

4.選擇 .NET 版本。 選擇穩定版本 .NET 6.0。

[如何在 C# 中將資料寫入 CSV 文件,圖 4:.NET Framework 選擇](/static-assets/excel/blog/how-to-write-data-in-csv-file-in-csharp-tutorial/how-to-write-data-in-csv-file-in-csharp-tutorial-4.webp)
**.NET Framework 選擇**

安裝 IronXL 庫

專案建立完成後,需要將 IronXL 庫安裝到專案中才能使用它。 按照以下步驟安裝。

  1. 從解決方案資源管理器或工具開啟 NuGet 套件管理器。

    如何在 C# 中將資料寫入 CSV 文件,圖 5:導覽至 NuGet 套件管理器 導覽至 NuGet 套件管理器

  2. 瀏覽 IronXL 庫並選擇目前項目。 點擊安裝。

    如何在 C# 中將資料寫入 CSV 文件,圖 6:在 NuGet 套件管理器 UI 中搜尋並安裝 IronXL 套件 在 NuGet 套件管理器 UI 中搜尋並安裝 IronXL 套件。

Program.cs檔案頂部新增以下命名空間:

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

在 C# 中建立新工作簿

IronXL 提供了建立空白工作簿的功能。 工作簿是包含多個工作表的電子表格。 資料儲存在單元格中。 CSV 檔案看起來也像是電子表格,但檔案副檔名為 CSV。

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

現在,讓我們在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

如果要為現有工作簿新增更多工作表,請使用CreateWorkSheet方法。

注意:如果 CSV 檔案已存在,則可以使用WorkBook.LoadCSV方法。 您可以查看此程式碼範例頁面,以了解如何載入現有的 CSV 檔案。

將資料寫入WorkSheet

使用 IronXL 編寫 CSV 檔案非常簡單。 它提供將資料寫入 CSV 檔案的 Excel 功能。可以使用儲存格引用將值新增至指定位置。 接下來,我將使用foreach循環添加一些員工的記錄。

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

在上面的程式碼範例中,建立了一個employeeNames數組,第一行設定了標題:ID、Name、Salary。 變數i也被初始化為值 2,它將從標題下方的第二行開始輸入記錄。 foreach循環處理清單中的每位員工,並將他們及其 ID 和薪資值新增至目前行。 在迴圈結束之前, i遞增,以便移動到下一行,處理下一筆記錄。

將資料儲存到 CSV 文件

最後一步是儲存 CSV 檔案。 IronXL 提供了SaveAsCsv方法,用於將工作簿儲存為 CSV 檔案。此方法的第一個參數是 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", ",");
' Save the modified workbook as a CSV file with a specified delimiter
workBook.SaveAsCsv("sample.csv", ",")
$vbLabelText   $csharpLabel

完整的程式碼如下:

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

輸出

如何在 C# 中將資料寫入 CSV 文件,圖 7:輸出的 CSV 文件 輸出的 CSV 檔案

摘要

本文介紹了一種使用 IronXL 在 C# 中編寫 CSV 檔案的簡單方法。 IronXL 也提供了輕鬆處理現有 CSV 檔案的功能。 它還允許您寫入 CSV 文件、建立新的 Excel 文件,並使用簡單的語法向其中寫入資料。 即使沒有安裝 Microsoft Office,IronXL 也可以用於讀取和寫入 Excel 檔案。 對於不同電子表格格式之間的轉換,您可以查看此程式碼範例頁面

IronXL 可免費用於開發,並可授權用於商業用途。 您也可以嘗試 IronXL 的商業用途免費試用版

常見問題解答

如何在 C# 中將資料寫入 CSV 檔案?

您可以使用 IronXL 的 `SaveAsCsv` 方法在 C# 中將資料匯出為 CSV 檔案。首先,建立工作簿和工作表,將資料寫入儲存格中,然後使用 `workBook.SaveAsCsv("filename.csv", ",");` 將資料儲存為 CSV 檔案。

在 C# 中建立寫入 CSV 檔案的控制台應用程式的步驟為何?

若要建立寫入 CSV 檔案的主控台應用程式,請在 Visual Studio 中建立新專案,選擇適當的 .NET 版本,並透過 NuGet 套件管理員安裝 IronXL。然後,使用 IronXL 建立工作簿,將資料加入工作表,並將其儲存為 CSV。

我可以不使用 Microsoft Excel 將資料寫入 CSV 檔案嗎?

是的,您可以使用 IronXL.Excel 將資料寫入 CSV 檔案,而無需 Microsoft Excel。它允許在不需要安裝 Excel 的情況下,以程式化的方式操作 Excel 和 CSV 檔案。

如何在 Visual Studio 專案中安裝 IronXL?

您可以在 Visual Studio 中開啟 NuGet Package Manager,搜尋「IronXL」,然後按一下「安裝」,將 IronXL 加入專案中,即可安裝 IronXL。這將使您能夠使用 IronXL 處理 Excel 和 CSV 檔案的功能。

IronXL 支援哪些檔案格式的匯出?

IronXL 支援將資料匯出成多種格式,包括 CSV、JSON、HTML、Binary、Byte Array、DataSet 和 DataTable,使其能滿足不同的資料處理需求。

IronXL 是否與不同的 .NET 版本相容?

是的,IronXL 與多種 .NET 版本相容,包括 .NET Core 2 和 3,以及 .NET 5、6 和 7,讓開發人員可以在不同的開發環境中靈活運用。

IronXL 可以用於商業專案嗎?

是的,IronXL 可以授權用於商業用途。它也提供免費試用版供開發使用,讓開發人員在承諾商業授權之前測試其功能。

如何使用 IronXL 在 C# 中建立新的工作簿和工作表?

您可以使用 `WorkBook.Create()` 來初始化工作簿物件,然後在其中加入新的工作表,藉此建立新的工作簿和工作表。這樣您就可以開始向工作表中寫入資料。

IronXL 是否需要任何 Office Interop 相依性?

不,IronXL 是一個獨立的函式庫,不需要任何 Office Interop 的相依性,因此很容易在不同平台的應用程式中使用和部署。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担产品测测试,产品开发和研究的责任时,Jordi 为持续的产品改进增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。