跳過到頁腳內容
使用 IRONXL

在 C# 中生成 Excel 文件

我們開發的應用程式會不斷地與 Excel 電子表格進行通信,以獲取用於評估和結果的數據。 能夠以 C# 程式設計方式產生 Excel 檔案真的很有幫助,這節省了我們開發的時間和精力。 在本教程中,我們將學習如何產生不同格式的 Excel 檔案、設定儲存格樣式以及使用高效的 C# 函數程式設計插入資料。

C# Excel 文件產生器

  • 用 IronXL 生成 Excel 檔案
  • 使用 C# 產生 .XLSX 和 .XLS 格式的 Excel 文件
  • 產生 CSV 文件
  • 在 C# 專案中產生 JSON、XML、TSV 檔案等。
How To Work related to 在 C# 中生成 Excel 文件

步驟 1

1. 使用 IronXL 產生 Excel 文件

使用 IronXL Excel for C# 庫產生 Excel 文件,提供一系列函數,用於在專案中產生和操作資料。 該庫可免費用於開發,待您準備好正式發佈時,即可購買許可證。要學習本教程,您可以下載 IronXL 進行生成,或透過 Visual Studio 和NuGet 庫存取它。


dotnet add package IronXL.Excel

操作指南

2. C# Excel 文件產生器概述

在商業應用開發中,我們經常需要以程式設計方式產生不同類型的 Excel 檔案。 為此,我們需要一種最簡單且快速的方法來自動產生不同類型的檔案並將它們儲存到所需位置。

安裝 IronXL 後,我們可以使用該函數產生不同類型的 Excel 檔案

  • 副檔名為.xlsx的 Excel 檔案。
  • 副檔名為.xls的 Excel 檔。
  • 逗號分隔值 ( .csv ) 檔案。
  • 製表符分隔值 ( .tsv ) 檔案。
  • JavaScript 物件表示法 ( .json ) 檔案。
  • 可擴充標記語言( .xml )檔案。

要產生任何類型的文件,首先我們需要建立一個 Excel WorkBook

// Generate a new WorkBook
WorkBook wb = WorkBook.Create();
// Generate a new WorkBook
WorkBook wb = WorkBook.Create();
' Generate a new WorkBook
Dim wb As WorkBook = WorkBook.Create()
$vbLabelText   $csharpLabel

上述程式碼行將會建立一個名為wb的新WorkBook 。 現在我們將建立一個WorkSheet物件。

// Generate a new WorkSheet
WorkSheet ws = wb.CreateWorkSheet("SheetName");
// Generate a new WorkSheet
WorkSheet ws = wb.CreateWorkSheet("SheetName");
' Generate a new WorkSheet
Dim ws As WorkSheet = wb.CreateWorkSheet("SheetName")
$vbLabelText   $csharpLabel

這將建立一個名為wsWorkSheet ,我們可以使用該工作表在 Excel 檔案中插入資料。


3. 產生 XLSX 檔(C#)

首先,我們按照上述步驟產生WorkBookWorkSheet

然後,我們將資料插入其中,建立副檔名為.xlsx檔案。為此,IronXL 提供了一個單元格尋址系統,允許我們以程式設計方式將資料插入到特定的單元格位址中。

// Insert data by cell addressing
ws["CellAddress"].Value = "MyValue";
// Insert data by cell addressing
ws["CellAddress"].Value = "MyValue";
' Insert data by cell addressing
ws("CellAddress").Value = "MyValue"
$vbLabelText   $csharpLabel

它會在指定的儲存格位址中插入新值"MyValue"。 同樣,我們可以根據需要向任意數量的單元格中插入資料。之後,我們將 Excel 檔案儲存到指定路徑,如下所示:

// Specify file path and name
wb.SaveAs("Path + FileName.xlsx");
// Specify file path and name
wb.SaveAs("Path + FileName.xlsx");
' Specify file path and name
wb.SaveAs("Path + FileName.xlsx")
$vbLabelText   $csharpLabel

這將在指定路徑建立一個副檔名為.xlsx的新 Excel 檔案。 儲存檔案時,別忘了在檔案名稱後面加上.xlsx副檔名。

若要進一步了解如何在 C# 專案中建立 Excel 工作簿,請查看此處的程式碼範例。

/**
 * Generate XLSX File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xlsx Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);

        // Create workSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";
        ws["C4"].Value = "IronXL";

        // Save the file as .xlsx
        wb.SaveAs("sample.xlsx");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate XLSX File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xlsx Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLSX);

        // Create workSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";
        ws["C4"].Value = "IronXL";

        // Save the file as .xlsx
        wb.SaveAs("sample.xlsx");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate XLSX File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook of .xlsx Extension
		Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)

		' Create workSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"
		ws("C4").Value = "IronXL"

		' Save the file as .xlsx
		wb.SaveAs("sample.xlsx")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

您可以在這裡看到新建立的 Excel 檔案sample.xlsx的螢幕截圖:

使用 C# 產生 Excel 文件,圖 1:儲存格 C4 中修改值的結果 在儲存格 C4 中修改值的結果


4. 產生 XLS 檔案(C#)

使用 IronXL 也可以產生.xls檔。 為此,我們將使用WorkBook.Create()函數,如下所示:

// Create a workbook with XLS format
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
// Create a workbook with XLS format
WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);
' Create a workbook with XLS format
Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)
$vbLabelText   $csharpLabel

這將建立一個擴展名為.xls新 Excel 檔案。 請記住,在為 Excel 檔案命名時,必須在檔案名稱後加上.xls副檔名,例如:

// Save the file as .xls
wb.SaveAs("Path + FileName.xls");
// Save the file as .xls
wb.SaveAs("Path + FileName.xls");
' Save the file as .xls
wb.SaveAs("Path + FileName.xls")
$vbLabelText   $csharpLabel

現在,讓我們來看一個如何產生副檔名為.xls Excel 檔案的範例:

/**
 * Generate XLS File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xls Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xls
        wb.SaveAs("sample.xls");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate XLS File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook of .xls Extension
        WorkBook wb = WorkBook.Create(ExcelFileFormat.XLS);

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xls
        wb.SaveAs("sample.xls");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate XLS File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook of .xls Extension
		Dim wb As WorkBook = WorkBook.Create(ExcelFileFormat.XLS)

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .xls
		wb.SaveAs("sample.xls")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

5. 產生 CSV 檔案(C#)

逗號分隔值 ( .csv ) 檔案在不同類型的組織中保存資料方面也發揮著非常重要的作用。 所以,我們還需要學習如何產生.csv文件,以及如何透過程式設計資料插入其中。

我們可以使用與上述相同的方法,但需要在儲存檔案名稱時指定.csv副檔名。 讓我們來看一個如何在 C# 專案中建立.csv檔案的範例:

/**
 * Generate CSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .csv
        wb.SaveAsCsv("sample.csv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate CSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .csv
        wb.SaveAsCsv("sample.csv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate CSV File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .csv
		wb.SaveAsCsv("sample.csv")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

要能夠與 CSV 檔案進行更多交互,您可以按照本教學讀取.csv檔案


6. 產生 TSV 檔案(C#)

有時我們需要產生製表符分隔值 ( .tsv ) 文件,並透過程式插入資料。

使用 IronXL,我們還可以產生.tsv副檔名文件,將資料插入其中,然後將其儲存到所需位置。

讓我們來看一個產生.tsv副檔名檔的範例:

/**
 * Generate TSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .tsv
        wb.SaveAsTsv("sample.tsv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate TSV File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .tsv
        wb.SaveAsTsv("sample.tsv");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate TSV File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .tsv
		wb.SaveAsTsv("sample.tsv")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

7. 產生 JSON 檔案(C#)

我們可以很肯定地說,JavaScript 物件表示法 ( .json ) 文件是最常見的資料文件,幾乎所有軟體開發公司都在使用它們。 因此,我們經常需要以 JSON 格式儲存資料。 為此,我們需要一種最簡單的方法來產生 JSON 格式的檔案並將資料插入其中。

在這種情況下,IronXL 是我們能夠輕鬆產生 C# 檔案的最佳選擇。 我們來看一個例子。

/**
 * Generate JSON File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "1";
        ws["A2"].Value = "john";
        ws["B1"].Value = "2";
        ws["B2"].Value = "alex";
        ws["C1"].Value = "3";
        ws["C2"].Value = "stokes";

        // Save the file as .json
        wb.SaveAsJson("sample.json");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate JSON File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "1";
        ws["A2"].Value = "john";
        ws["B1"].Value = "2";
        ws["B2"].Value = "alex";
        ws["C1"].Value = "3";
        ws["C2"].Value = "stokes";

        // Save the file as .json
        wb.SaveAsJson("sample.json");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate JSON File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "1"
		ws("A2").Value = "john"
		ws("B1").Value = "2"
		ws("B2").Value = "alex"
		ws("C1").Value = "3"
		ws("C2").Value = "stokes"

		' Save the file as .json
		wb.SaveAsJson("sample.json")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

請查看新建立的 JSON 檔案sample.json的螢幕截圖:

使用 C# 產生 Excel 文件,圖 2:在 Visual Studio 中導航到 NuGet 套件管理器 在 Visual Studio 中導覽至 NuGet 套件管理器


8. 產生 XML 檔案(C#)

在商業應用程式開發中,我們經常需要將資料儲存為可擴展標記語言( .xml )檔案格式。 這一點很重要,因為.xml檔案資料既可以被人讀取,也可以被機器讀取。

透過以下範例,我們將學習如何為 C# 產生.xml檔案並以程式設計方式插入資料。

/**
 * Generate XML File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xml
        wb.SaveAsXml("sample.xml");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
/**
 * Generate XML File
 */
using System;
using IronXL;

class Program
{
    static void Main(string[] args)
    {
        // Create new WorkBook
        WorkBook wb = WorkBook.Create();

        // Create WorkSheet
        WorkSheet ws = wb.CreateWorkSheet("Sheet1");

        // Insert data in the cells of WorkSheet
        ws["A1"].Value = "Hello";
        ws["A2"].Value = "World";

        // Save the file as .xml
        wb.SaveAsXml("sample.xml");

        Console.WriteLine("Successfully created.");
        Console.ReadKey();
    }
}
'''
''' * Generate XML File
''' 
Imports System
Imports IronXL

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		' Create new WorkBook
		Dim wb As WorkBook = WorkBook.Create()

		' Create WorkSheet
		Dim ws As WorkSheet = wb.CreateWorkSheet("Sheet1")

		' Insert data in the cells of WorkSheet
		ws("A1").Value = "Hello"
		ws("A2").Value = "World"

		' Save the file as .xml
		wb.SaveAsXml("sample.xml")

		Console.WriteLine("Successfully created.")
		Console.ReadKey()
	End Sub
End Class
$vbLabelText   $csharpLabel

您可以閱讀更多關於如何以程式設計方式轉換 Excel 電子表格和檔案以便在 C# 專案中使用的資訊。

IronXL 庫還提供了與 Excel 檔案互動的各種功能,例如儲存格資料格式設定合併儲存格插入數學函數,甚至管理圖表。


教程快速存取

IronXL 生成器文檔

請閱讀完整文檔,以了解 IronXL 如何產生 C# 專案所需的所有 Excel 格式的文件。

IronXL 生成器文檔
Documentation related to 教程快速存取

常見問題解答

如何在 C# 中產生 Excel 檔案?

您可以使用 IronXL.Excel 在 C# 中生成 Excel 檔案。首先建立 WorkBook 和 WorkSheet,使用單元格定址系統插入您的資料,並使用 IronXL 的方法以所需格式儲存檔案。

用 C# 程式化操作 Excel 檔案的步驟為何?

若要以 C# 程式化方式操作 Excel 檔案,請透過 NuGet 套件管理員安裝 IronXL.Excel,建立 WorkBook 和 WorkSheet,使用 C# 程式碼插入和操作資料,並將變更以您偏好的檔案格式儲存。

如何使用 C# 將 Excel 檔案儲存為 JSON?

使用 IronXL,您可以透過建立 WorkBook 和 WorkSheet、新增必要的資料,並使用 SaveAsJson 方法以 JSON 格式匯出檔案,將 Excel 檔案儲存為 JSON 格式。

我可以使用 C# 將 Excel 檔案轉換為 CSV 嗎?

是的,IronXL 可以讓您使用 C# 將 Excel 檔案轉換為 CSV。您需要將 Excel 檔案載入 WorkBook,依需要處理,並使用 SaveAsCsv 方法匯出。

使用 C# 可以將 Excel 資料匯出成哪些格式?

使用 IronXL.Excel,您可以將 Excel 資料匯出成各種格式,例如 XLSX、CSV、TSV、JSON 和 XML。這種多樣性有利於 C# 專案中不同的資料處理需求。

如何在 C# 中安裝 IronXL.Excel 操作?

若要在 C# 中安裝 IronXL 以執行 Excel 作業,請使用 Visual Studio 中的 NuGet 套件管理器,並使用指令 dotnet add package IronXL.Excel 進行安裝。

IronXL 是否適用於涉及 Excel 檔案的商業應用程式?

IronXL.Excel 非常適合商業應用,因為它簡化了以程式化方式產生和處理 Excel 檔案的過程,使其能有效率地自動執行資料處理工作。

開發期間可以免費使用 IronXL 嗎?

IronXL 可免費用於開發目的。然而,當您準備在生產環境中部署或使用該函式庫時,則需要取得授權。

在 C# 中生成 Excel 檔案時,如何為儲存格加上樣式?

使用 IronXL 時,您可以透過函式庫中提供的方法設定字型大小、顏色和樣式等屬性,為產生的 Excel 檔案中的儲存格建立樣式。

我可以用 C# 從 Excel 資料產生 XML 檔案嗎?

是的,您可以使用 IronXL 從 Excel 資料產生 XML 檔案。在 WorkBook 和 WorkSheet 中準備好資料後,使用 SaveAsXml 方法將資料匯出為 XML 格式。

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