跳過到頁腳內容
使用 IRONXL

在 C# 中生成 Excel 文件

我們開發的應用程式不斷地與 Excel 試算表進行溝通,以獲取資料進行評估和結果。 能夠使用 C# 程式碼生成 Excel 文件,這對我們的開發來說非常有幫助,可以節省時間和精力。 在本教程中,我們將學習如何生成不同格式的 Excel 文件,設定儲存格樣式,並使用高效函數程序化地插入數據。

class="learnn-how-section">
class="row">
class="col-sm-6">

C# Excel 文件生成器

  • 使用 IronXL 生成 Excel 文件
  • 在 C# 中生成 .XLSX 和 .XLS 格式的 Excel 文件
  • 生成 CSV 文件
  • 在 C# 專案中生成 JSON、XML、TSV 文件等
class="col-sm-6">
class="download-card"> How To Work related to 在 C# 中生成 Excel 文件

class="tutorial-segment-title">步驟 1

1. 使用 IronXL 生成 Excel 文件

使用 IronXL Excel for C# 庫生成 Excel 文件,提供一系列用于生成和處理專案數據的功能。 The library is free for development, with licenses available when you're ready to push live. To follow this tutorial, you can download IronXL for generating or access it through Visual Studio and NuGet gallery.


dotnet add package IronXL.Excel

class="tutorial-segment-title">如何教程

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 是可以輕鬆生成這些文件的最佳選擇。 讓我們看一下示例。

/**
 * 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 library also offers a wide range of features to interact with Excel files such as cell data formatting, merging cells, inserting math functions, and even managing charts.


class="tutorial-segment-title">教程快速訪問

class="tutorial-section">
class="row">
class="col-sm-8">

IronXL 生成器文档

閱讀完整的文檔,了解 IronXL 如何生成您 C# 專案所需的每一種 Excel 格式的文件。

IronXL 生成器文档
class="col-sm-4">
class="tutorial-image"> Documentation related to class=教程快速訪問" class="img-responsive add-shadow img-responsive img-popup" src="/img/svgs/documentation.svg" loading="lazy">

常見問題解答

我如何能在 C# 中生成 Excel 檔案?

您可以使用 IronXL 在 C# 中生成 Excel 檔案。首先創建 WorkBook 和 WorkSheet,使用 Cell Addressing System 插入資料,然後使用 IronXL 的方法將檔案存成所需格式。

程式化操控 Excel 檔案的步驟是什麼?

要在 C# 中程式化操控 Excel 檔案,請通過 NuGet 套件管理器安裝 IronXL,創建 WorkBook 和 WorkSheet,使用 C# 語法插入並操控資料,再保存為您偏好的檔案格式。

我如何能使用 C# 將 Excel 檔案保存為 JSON?

使用 IronXL,您可以通過創建 WorkBook 和 WorkSheet,添加必要的資料,然後使用 SaveAsJson 方法將檔案導出為 JSON 格式。

我能使用 C# 將 Excel 檔案轉換成 CSV 嗎?

是的,IronXL 允許您在 C# 中將 Excel 檔案轉換成 CSV。您需要將 Excel 檔案加載到 WorkBook 中,按需處理,並使用 SaveAsCsv 方法導出。

使用 C# 我可以將 Excel 資料導出到什麼格式?

使用 IronXL,您可以將 Excel 資料導出到多種格式,如 XLSX、CSV、TSV、JSON 和 XML。這種多功能性對 C# 項目的各類資料處理需求很有幫助。

我如何安裝 IronXL 以便在 C# 中進行 Excel 操作?

要在 C# 中安裝 IronXL 用於 Excel 操作,請在 Visual Studio 中使用 NuGet 套件管理器,執行命令 dotnet add package IronXL.Excel

IronXL 適用於涉及 Excel 檔案的商務應用嗎?

IronXL 對於商務應用非常適用,因其簡化了程式化生成和操控 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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。