跳至頁尾內容
USING IRONXL

如何在 C# 中處理 Excel 檔案:圖 1 - 教學課程

IronXL 是一個強大的 C# 程式庫,使開發者能夠讀取、寫入和操作 Excel 文件,而無需安裝 Microsoft Excel,提供跨平台相容性,並支援像 XLS、XLSX、CSV 等格式,通過直觀的 API。

如何在 C# 中使用 Excel 工作簿?

  1. 建立一個 Visual Studio 專案並新增 IronXL NuGet 套件。
  2. 無需使用 Interop 來建立 Excel 文件。
  3. 使用 IronXL 為 Excel 文件新增樣式。
  4. 從 Excel 讀取值並進行計算。
  5. 將 Excel 轉換為 HTML 以供網頁使用。

什麼是 IronXL 程式庫?

IronXL 是一個強大的 .NET 程式庫,能簡化 Excel 文件的操作。 它具有 直觀的 API,簡化了 Excel 文件的操作,支援多種格式,如 XLS、XLSX 和 CSV。 這種多功能性允許輕鬆操作單元格值、公式和格式。 IronXL 針對效能進行優化,可有效處理大型文件和複雜的資料操作,同時確保有效的記憶體使用。 其跨平台相容性增強了其在不同操作系統上的實用性。 這是其主要功能和優勢:

IronXL 的主要功能是什麼?

  1. 導入和導出:

  2. 資料操作:

  3. 樣式和格式化:

  4. 安全性:

  5. 跨平台相容性:

為什麼我應該選擇 IronXL 而不是其他 Excel 程式庫?

  1. 不需要 Microsoft Office:IronXL 無需安裝 Microsoft Office,使其輕量且易於部署。
  2. 易於使用:API 直觀且易於使用,使開發者可以快速將 Excel 功能整合到應用程式中。
  3. 效能:IronXL 經過效能優化,確保快速有效地處理大型 Excel 文件。
  4. 通用性:適用於範圍廣泛的應用,包括網頁、桌面和基於雲端的解決方案。
  5. 全面的文件:提供廣泛的文件和範例,讓開發者更容易入門及找到常見問題的解決方案。

如何開始使用 IronXL?

要在您的 .NET 專案中使用 IronXL,請確保您的開發環境符合以下先決條件:

使用 IronXL 的先決條件是什麼?

  1. .NET Framework:IronXL 支援 .NET Framework 4.5 及以上
  2. .NET Core 和 .NET Standard:相容於 .NET Core 2、3、5、6、7、8 和 9
  3. 作業系統:可在 Windows、macOS 和 Linux 上運行。 Compatible with Docker, Azure, and AWS.
  4. 不需要 Microsoft Office:IronXL 不需要 Office 或 Excel Interop
  5. 程式碼編輯器:任何 C# 程式碼編輯器,例如 Visual Studio。

如何在我的專案中安裝 IronXL?

您可以通過 Visual Studio 中的 NuGet 封裝管理器或使用封裝管理器主控台使用以下指令安裝 IronXL:

dotnet add package IronXL.Excel --version 2024.8.5

有關更詳細的安裝說明,包括 Blazor.NET MAUIVB.NET 專案的設置,請參閱官方文件

如何用 IronXL 建立第一個 Excel 文件?

讓我們開發一個 Visual Studio 專案並新增 IronXL 程式庫,以開始使用 Excel 文件。

如何建立 Visual Studio 專案並新增 IronXL?

打開 Microsoft Visual Studio 並選擇"建立新專案"以開始。

Visual Studio 2022 開始螢幕顯示選項以打開最近的專案、克隆倉庫、開啟專案/解決方案、打開本機資料夾或建立新專案。

選擇您喜好的專案模板。在這裡,我們選擇了控制台應用程式以求簡單。

Visual Studio 的

現在輸入專案的名稱和位置。

Visual Studio 專案配置對話框顯示 C# 控制台應用程式的新設置,名稱為

選擇您偏好的 .NET Framework 版本。 我們選擇了我們機器上可用的最新版本。

Visual Studio 專案建立對話框顯示選擇了 .NET 8.0 框架的控制台應用配置,以及頂級語句和 AOT 發佈的附加選項

當您點擊"建立"按鈕後,專案將被建立並準備好使用。 打開解決方案資源管理器以查看專案文件。

Visual Studio NuGet 套件管理器顯示了為名為 WorkingWithIronXL 的 C# 專案選擇的 IronXL.Excel 套件的設置,版本為 2024.8.5

現在,我們按照上圖通過 NuGet 套件管理器安裝 IronXL 程式庫。

如何在沒有 Interop 的情況下建立 Excel 文件?

現在讓我們在不使用 Microsoft Interop 程式庫的情況下建立一個 Excel 文件。 IronXL 提供了一種簡單而直觀的方法來以程式碼建立電子表格

using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create new Excel WorkBook Object
            WorkBook workBook = WorkBook.Create();
            // Create WorkSheet
            WorkSheet workSheet = workBook.CreateWorkSheet("newXlDemo");
            // Add data in new worksheet
            workSheet["A1"].Value = "IronXL is the best Excel library";           
            // Save the Excel file as XLSX
            workBook.SaveAs("myIronXlDemo.xlsx");
        }
    }
}
using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create new Excel WorkBook Object
            WorkBook workBook = WorkBook.Create();
            // Create WorkSheet
            WorkSheet workSheet = workBook.CreateWorkSheet("newXlDemo");
            // Add data in new worksheet
            workSheet["A1"].Value = "IronXL is the best Excel library";           
            // Save the Excel file as XLSX
            workBook.SaveAs("myIronXlDemo.xlsx");
        }
    }
}
Imports IronXL

Namespace WorkingWithIronXL
	Public Class Program
		Public Shared Sub Main()
			' Create new Excel WorkBook Object
			Dim workBook As WorkBook = WorkBook.Create()
			' Create WorkSheet
			Dim workSheet As WorkSheet = workBook.CreateWorkSheet("newXlDemo")
			' Add data in new worksheet
			workSheet("A1").Value = "IronXL is the best Excel library"
			' Save the Excel file as XLSX
			workBook.SaveAs("myIronXlDemo.xlsx")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼說明

  1. 我們新增 IronXL 命名空間以開始使用該程式庫。
  2. 使用 WorkBook.Create() 建立一個 Excel 物件以建立 XLSX 文件。
  3. 調用 CreateWorkSheet 方法來建立工作簿內的工作表。
  4. 使用 workSheet["A1"].Value 向單元格新增數值。
  5. 通過提供一個文件名來使用 workBook.SaveAs 保存 Excel 文件。

輸出 Excel 文件

Excel 電子表格在以程式碼建立的 Excel 文件中,在單元格 A1 顯示了

為什麼 IronXL 不需要 Interop?

與傳統方法依賴於Microsoft Excel Interop不同,IronXL 是一個獨立的 .NET 程式庫,直接讀寫 Excel 文件。 這意味著:

  • 不需要安裝 Microsoft Office
  • 更好的效能和記憶體使用
  • Cross-platform compatibility (Linux, macOS, Docker)
  • 沒有 COM 物件清理問題
  • 執行緒安全操作

我可以將文件儲存為哪些格式?

IronXL 支援保存為多種格式

// Save as different Excel formats
workBook.SaveAs("file.xlsx"); // Excel 2007+ format
workBook.SaveAs("file.xls");  // Excel 97-2003 format
workBook.SaveAs("file.xlsm"); // Excel with macros

// Export to other formats
workBook.SaveAsCsv("file.csv", ",");  // CSV with comma delimiter
workBook.SaveAsJson("file.json");     // JSON format
workBook.SaveAsXml("file.xml");       // XML format
// Save as different Excel formats
workBook.SaveAs("file.xlsx"); // Excel 2007+ format
workBook.SaveAs("file.xls");  // Excel 97-2003 format
workBook.SaveAs("file.xlsm"); // Excel with macros

// Export to other formats
workBook.SaveAsCsv("file.csv", ",");  // CSV with comma delimiter
workBook.SaveAsJson("file.json");     // JSON format
workBook.SaveAsXml("file.xml");       // XML format
' Save as different Excel formats
workBook.SaveAs("file.xlsx") ' Excel 2007+ format
workBook.SaveAs("file.xls")  ' Excel 97-2003 format
workBook.SaveAs("file.xlsm") ' Excel with macros

' Export to other formats
workBook.SaveAsCsv("file.csv", ",")  ' CSV with comma delimiter
workBook.SaveAsJson("file.json")     ' JSON format
workBook.SaveAsXml("file.xml")       ' XML format
$vbLabelText   $csharpLabel

我如何處理文件建立過程中的錯誤?

IronXL 提供了全面的錯誤處理。 這是最佳實踐範例:

try 
{
    WorkBook workBook = WorkBook.Create();
    WorkSheet workSheet = workBook.CreateWorkSheet("Demo");
    workSheet["A1"].Value = "Sample Data";

    // Check if directory exists
    string directory = @"C:\ExcelFiles\";
    if (!Directory.Exists(directory))
    {
        Directory.CreateDirectory(directory);
    }

    workBook.SaveAs(Path.Combine(directory, "output.xlsx"));
}
catch (Exception ex)
{
    Console.WriteLine($"Error creating Excel file: {ex.Message}");
}
try 
{
    WorkBook workBook = WorkBook.Create();
    WorkSheet workSheet = workBook.CreateWorkSheet("Demo");
    workSheet["A1"].Value = "Sample Data";

    // Check if directory exists
    string directory = @"C:\ExcelFiles\";
    if (!Directory.Exists(directory))
    {
        Directory.CreateDirectory(directory);
    }

    workBook.SaveAs(Path.Combine(directory, "output.xlsx"));
}
catch (Exception ex)
{
    Console.WriteLine($"Error creating Excel file: {ex.Message}");
}
Imports System
Imports System.IO

Try
    Dim workBook As WorkBook = WorkBook.Create()
    Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Demo")
    workSheet("A1").Value = "Sample Data"

    ' Check if directory exists
    Dim directory As String = "C:\ExcelFiles\"
    If Not Directory.Exists(directory) Then
        Directory.CreateDirectory(directory)
    End If

    workBook.SaveAs(Path.Combine(directory, "output.xlsx"))
Catch ex As Exception
    Console.WriteLine($"Error creating Excel file: {ex.Message}")
End Try
$vbLabelText   $csharpLabel

如何使用 IronXL 為 Excel 文件新增樣式?

現在讓我們看看如何向 Excel 單元格新增樣式。 IronXL 提供了全面的樣式選項,可建立專業外觀的電子表格。

using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create a new workbook
            WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
            // Create a new worksheet
            WorkSheet workSheet = workBook.CreateWorkSheet("StyledSheet");
            // Add multiple values to cells
            workSheet["A1"].Value = "This Styled Text with Awesome IronXL library";
            workSheet["A2"].Value = 999999;
            // Apply styles to cells
            workSheet["A1"].Style.Font.Bold = true;
            workSheet["A1"].Style.Font.Italic = true;
            workSheet["A1"].Style.Font.Height = 14;
            workSheet["A1"].Style.Font.Color = "#FF0000"; // Red color
            workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
            workSheet["A2"].Style.BottomBorder.SetColor("#00FF00"); // Green color
            // Save the workbook
            workBook.SaveAs("myIronXlWriteDemo.xlsx");
        }
    }
}
using IronXL;

namespace WorkingWithIronXL
{
    public class Program
    {
        public static void Main()
        {
            // Create a new workbook
            WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);
            // Create a new worksheet
            WorkSheet workSheet = workBook.CreateWorkSheet("StyledSheet");
            // Add multiple values to cells
            workSheet["A1"].Value = "This Styled Text with Awesome IronXL library";
            workSheet["A2"].Value = 999999;
            // Apply styles to cells
            workSheet["A1"].Style.Font.Bold = true;
            workSheet["A1"].Style.Font.Italic = true;
            workSheet["A1"].Style.Font.Height = 14;
            workSheet["A1"].Style.Font.Color = "#FF0000"; // Red color
            workSheet["A2"].Style.BottomBorder.Type = IronXL.Styles.BorderType.Double;
            workSheet["A2"].Style.BottomBorder.SetColor("#00FF00"); // Green color
            // Save the workbook
            workBook.SaveAs("myIronXlWriteDemo.xlsx");
        }
    }
}
Imports IronXL

Namespace WorkingWithIronXL
	Public Class Program
		Public Shared Sub Main()
			' Create a new workbook
			Dim workBook As WorkBook = WorkBook.Create(ExcelFileFormat.XLSX)
			' Create a new worksheet
			Dim workSheet As WorkSheet = workBook.CreateWorkSheet("StyledSheet")
			' Add multiple values to cells
			workSheet("A1").Value = "This Styled Text with Awesome IronXL library"
			workSheet("A2").Value = 999999
			' Apply styles to cells
			workSheet("A1").Style.Font.Bold = True
			workSheet("A1").Style.Font.Italic = True
			workSheet("A1").Style.Font.Height = 14
			workSheet("A1").Style.Font.Color = "#FF0000" ' Red color
			workSheet("A2").Style.BottomBorder.Type = IronXL.Styles.BorderType.Double
			workSheet("A2").Style.BottomBorder.SetColor("#00FF00") ' Green color
			' Save the workbook
			workBook.SaveAs("myIronXlWriteDemo.xlsx")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼說明

  1. 使用 WorkBook.Create 建立 Excel 文件。
  2. 使用 workBook.CreateWorkSheet 建立工作表。
  3. 使用 workSheet["A1"].Value 向單元格新增數值。
  4. 使用屬性 workSheet["A1"].Style.Font.Bold 向單元格新增樣式。
  5. 使用 workBook.SaveAs 保存工作簿。

輸出 Excel 文件

Excel 電子表格在 A1 單元格中顯示了紅色斜體文字

有哪些樣式選項可以使用?

IronXL 提供豐富的樣式選項,包括:

我如何將樣式應用於多個單元格?

您可以有效地將樣式應用於多個範圍的單元格

// Apply styles to a range
var range = workSheet["A1:D10"];
foreach (var cell in range)
{
    cell.Style.Font.Bold = true;
    cell.Style.Font.Color = "#0000FF"; // Blue
    cell.Style.SetBackgroundColor("#FFFF00"); // Yellow background
}
// Apply styles to a range
var range = workSheet["A1:D10"];
foreach (var cell in range)
{
    cell.Style.Font.Bold = true;
    cell.Style.Font.Color = "#0000FF"; // Blue
    cell.Style.SetBackgroundColor("#FFFF00"); // Yellow background
}
' Apply styles to a range
Dim range = workSheet("A1:D10")
For Each cell In range
    cell.Style.Font.Bold = True
    cell.Style.Font.Color = "#0000FF" ' Blue
    cell.Style.SetBackgroundColor("#FFFF00") ' Yellow background
Next
$vbLabelText   $csharpLabel

我可以使用條件格式嗎?

是的,IronXL 支援條件格式

// Add conditional formatting rule
var rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(
    ComparisonOperator.GreaterThan, "100");
rule.FontFormatting.Bold = true;
rule.FontFormatting.FontColor = "#FF0000"; // Red for values > 100
workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule);
// Add conditional formatting rule
var rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(
    ComparisonOperator.GreaterThan, "100");
rule.FontFormatting.Bold = true;
rule.FontFormatting.FontColor = "#FF0000"; // Red for values > 100
workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule);
' Add conditional formatting rule
Dim rule = workSheet.ConditionalFormatting.CreateConditionalFormattingRule(ComparisonOperator.GreaterThan, "100")
rule.FontFormatting.Bold = True
rule.FontFormatting.FontColor = "#FF0000" ' Red for values > 100
workSheet.ConditionalFormatting.AddConditionalFormatting("A1:A10", rule)
$vbLabelText   $csharpLabel

如何從 Excel 中讀取值並計算?

現在讓我們看看如何使用 IronXL 讀取 Excel 文件 並進行計算。 IronXL 支持各種數學函式進行資料分析。

using IronXL;
using System;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ReadData()
        {
            // Load the Excel worksheet
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            // Select the first worksheet
            WorkSheet workSheet = workBook.WorkSheets[0];
            // Read a specific cell value
            int cellValue = workSheet["A2"].IntValue;
            Console.WriteLine($"Value in A2: {cellValue}");
            // Read a range of cells
            foreach (var cell in workSheet["A1:H10"])
            {
                Console.Write($"{cell.Text}\t");
                if(cell.AddressString.Contains("H"))
                {
                    Console.WriteLine();
                }
            }
            // Calculate aggregate values
            decimal sum = workSheet["F2:F10"].Sum();
            Console.WriteLine($"Sum of F2:F10: {sum}");
        }
    }
}
using IronXL;
using System;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ReadData()
        {
            // Load the Excel worksheet
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            // Select the first worksheet
            WorkSheet workSheet = workBook.WorkSheets[0];
            // Read a specific cell value
            int cellValue = workSheet["A2"].IntValue;
            Console.WriteLine($"Value in A2: {cellValue}");
            // Read a range of cells
            foreach (var cell in workSheet["A1:H10"])
            {
                Console.Write($"{cell.Text}\t");
                if(cell.AddressString.Contains("H"))
                {
                    Console.WriteLine();
                }
            }
            // Calculate aggregate values
            decimal sum = workSheet["F2:F10"].Sum();
            Console.WriteLine($"Sum of F2:F10: {sum}");
        }
    }
}
Imports Microsoft.VisualBasic
Imports IronXL
Imports System

Namespace WorkingWithIronXL
	Friend Class IronXlDemo
		Public Shared Sub ReadData()
			' Load the Excel worksheet
			Dim workBook As WorkBook = WorkBook.Load("sampleEmployeeData.xlsx")
			' Select the first worksheet
			Dim workSheet As WorkSheet = workBook.WorkSheets(0)
			' Read a specific cell value
			Dim cellValue As Integer = workSheet("A2").IntValue
			Console.WriteLine($"Value in A2: {cellValue}")
			' Read a range of cells
			For Each cell In workSheet("A1:H10")
				Console.Write($"{cell.Text}" & vbTab)
				If cell.AddressString.Contains("H") Then
					Console.WriteLine()
				End If
			Next cell
			' Calculate aggregate values
			Dim sum As Decimal = workSheet("F2:F10").Sum()
			Console.WriteLine($"Sum of F2:F10: {sum}")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼說明

  1. 使用 WorkBook.Load 載入 Excel 文件
  2. 存取工作簿中的第一個工作表。
  3. 讀取特定單元格的值並使用 Console.WriteLine 顯示它。
  4. 遍歷一個單元格範圍並列印每個值。 在列 H 後列印新行。
  5. 計算範圍 F2:F10 的值的總和並列印它。

輸入 Excel

Excel 電子表格顯示了員工資料,列名有 ID、名、姓、性別、國家、年齡、日期和唯一標識符,顯示了 9 行的樣本員工記錄。

輸出

控制台輸出顯示10 行人員記錄的資料表,包括姓名、性別、國家、年齡、日期和 ID 字段,隨後是列 F2:F10 總和計算為 323。

我可以從單元格中讀取什麼資料型別?

IronXL 支持從單元格中讀取各種資料型別:

// Different ways to read cell values
string textValue = workSheet["A1"].StringValue;
int intValue = workSheet["B1"].IntValue;
decimal decimalValue = workSheet["C1"].DecimalValue;
double doubleValue = workSheet["D1"].DoubleValue;
DateTime dateValue = workSheet["E1"].DateTimeValue;
bool boolValue = workSheet["F1"].BoolValue;

// Read formula results
string formulaResult = workSheet["G1"].FormattedCellValue;
// Different ways to read cell values
string textValue = workSheet["A1"].StringValue;
int intValue = workSheet["B1"].IntValue;
decimal decimalValue = workSheet["C1"].DecimalValue;
double doubleValue = workSheet["D1"].DoubleValue;
DateTime dateValue = workSheet["E1"].DateTimeValue;
bool boolValue = workSheet["F1"].BoolValue;

// Read formula results
string formulaResult = workSheet["G1"].FormattedCellValue;
' Different ways to read cell values
Dim textValue As String = workSheet("A1").StringValue
Dim intValue As Integer = workSheet("B1").IntValue
Dim decimalValue As Decimal = workSheet("C1").DecimalValue
Dim doubleValue As Double = workSheet("D1").DoubleValue
Dim dateValue As DateTime = workSheet("E1").DateTimeValue
Dim boolValue As Boolean = workSheet("F1").BoolValue

' Read formula results
Dim formulaResult As String = workSheet("G1").FormattedCellValue
$vbLabelText   $csharpLabel

我如何處理空或null的單元格?

IronXL 提供了安全處理空位的方法:

// Check if cell is empty
if (workSheet["A1"].IsEmpty)
{
    Console.WriteLine("Cell A1 is empty");
}

// Use null-coalescing for safe value reading
string value = workSheet["A1"].StringValue ?? "Default Value";

// Check for specific content types
if (workSheet["B1"].IsNumeric)
{
    decimal numValue = workSheet["B1"].DecimalValue;
}
// Check if cell is empty
if (workSheet["A1"].IsEmpty)
{
    Console.WriteLine("Cell A1 is empty");
}

// Use null-coalescing for safe value reading
string value = workSheet["A1"].StringValue ?? "Default Value";

// Check for specific content types
if (workSheet["B1"].IsNumeric)
{
    decimal numValue = workSheet["B1"].DecimalValue;
}
' Check if cell is empty
If workSheet("A1").IsEmpty Then
    Console.WriteLine("Cell A1 is empty")
End If

' Use null-coalescing for safe value reading
Dim value As String = If(workSheet("A1").StringValue, "Default Value")

' Check for specific content types
If workSheet("B1").IsNumeric Then
    Dim numValue As Decimal = workSheet("B1").DecimalValue
End If
$vbLabelText   $csharpLabel

有哪些匯總函式可用?

IronXL 支持各種匯總函式

// Available aggregate functions
decimal sum = workSheet["A1:A10"].Sum();
decimal avg = workSheet["A1:A10"].Avg();
decimal min = workSheet["A1:A10"].Min();
decimal max = workSheet["A1:A10"].Max();
int count = workSheet["A1:A10"].Count();
// Available aggregate functions
decimal sum = workSheet["A1:A10"].Sum();
decimal avg = workSheet["A1:A10"].Avg();
decimal min = workSheet["A1:A10"].Min();
decimal max = workSheet["A1:A10"].Max();
int count = workSheet["A1:A10"].Count();
' Available aggregate functions
Dim sum As Decimal = workSheet("A1:A10").Sum()
Dim avg As Decimal = workSheet("A1:A10").Avg()
Dim min As Decimal = workSheet("A1:A10").Min()
Dim max As Decimal = workSheet("A1:A10").Max()
Dim count As Integer = workSheet("A1:A10").Count()
$vbLabelText   $csharpLabel

如何將 Excel 轉換為 HTML 以便用於網頁?

讓我們看看如何將 Excel 轉換為 HTML以供網頁使用。 這對於在網路應用程式中顯示 Excel 資料特別有用。

using IronXL;
using IronXL.Options;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ConvertToHtml()
        {
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            var options = new HtmlExportOptions()
            {
                // Set row/column numbers visible in HTML document
                OutputRowNumbers = true,
                OutputColumnHeaders = true,
                // Set hidden rows/columns visible in HTML document
                OutputHiddenRows = true,
                OutputHiddenColumns = true,
                // Set leading spaces as non-breaking
                OutputLeadingSpacesAsNonBreaking = true
            };
            // Export workbook to the HTML file
            workBook.ExportToHtml("workBook.html", options);
        }
    }
}
using IronXL;
using IronXL.Options;

namespace WorkingWithIronXL
{
    internal class IronXlDemo
    {
        public static void ConvertToHtml()
        {
            WorkBook workBook = WorkBook.Load("sampleEmployeeData.xlsx");
            var options = new HtmlExportOptions()
            {
                // Set row/column numbers visible in HTML document
                OutputRowNumbers = true,
                OutputColumnHeaders = true,
                // Set hidden rows/columns visible in HTML document
                OutputHiddenRows = true,
                OutputHiddenColumns = true,
                // Set leading spaces as non-breaking
                OutputLeadingSpacesAsNonBreaking = true
            };
            // Export workbook to the HTML file
            workBook.ExportToHtml("workBook.html", options);
        }
    }
}
Imports IronXL
Imports IronXL.Options

Namespace WorkingWithIronXL
	Friend Class IronXlDemo
		Public Shared Sub ConvertToHtml()
			Dim workBook As WorkBook = WorkBook.Load("sampleEmployeeData.xlsx")
			Dim options = New HtmlExportOptions() With {
				.OutputRowNumbers = True,
				.OutputColumnHeaders = True,
				.OutputHiddenRows = True,
				.OutputHiddenColumns = True,
				.OutputLeadingSpacesAsNonBreaking = True
			}
			' Export workbook to the HTML file
			workBook.ExportToHtml("workBook.html", options)
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

程式碼說明

  1. 使用 Load 方法載入 Excel 文件。
  2. 使用 HtmlExportOptions 設置 HTML 轉換選項。
  3. 使用 ExportToHtml 方法將其進行轉換並另存為 HTML。

輸入

Excel 電子表格顯示了樣本員工資料,列名有 ID、名、姓、性別、國家、年齡、日期和 Id,包含 9 行的員工資訊。

輸出

HTML 表格顯示了 Excel 資料,列名有名、姓、性別、國家、年齡、日期和 Id,顯示了 9 行的樣本員工資料。

有哪些 HTML 導出選項可用?

IronXL 提供了多種HTML 導出選項

var htmlOptions = new HtmlExportOptions()
{
    // Table formatting options
    OutputRowNumbers = true,
    OutputColumnHeaders = true,

    // Visibility options  
    OutputHiddenRows = false,
    OutputHiddenColumns = false,

    // Formatting preservation
    OutputLeadingSpacesAsNonBreaking = true,

    // Custom CSS class
    TableCssClass = "excel-table"
};
var htmlOptions = new HtmlExportOptions()
{
    // Table formatting options
    OutputRowNumbers = true,
    OutputColumnHeaders = true,

    // Visibility options  
    OutputHiddenRows = false,
    OutputHiddenColumns = false,

    // Formatting preservation
    OutputLeadingSpacesAsNonBreaking = true,

    // Custom CSS class
    TableCssClass = "excel-table"
};
Dim htmlOptions As New HtmlExportOptions() With {
    .OutputRowNumbers = True,
    .OutputColumnHeaders = True,
    .OutputHiddenRows = False,
    .OutputHiddenColumns = False,
    .OutputLeadingSpacesAsNonBreaking = True,
    .TableCssClass = "excel-table"
}
$vbLabelText   $csharpLabel

如何在 HTML 中保留格式?

IronXL 自動在導出為 HTML 時保留基本格式。 對於高級格式保留:

// Export with inline CSS styles
workBook.ExportToHtml("styled.html", new HtmlExportOptions
{
    OutputRowNumbers = false,
    OutputColumnHeaders = true,
    // Preserves cell styles as inline CSS
    PreserveStyles = true
});
// Export with inline CSS styles
workBook.ExportToHtml("styled.html", new HtmlExportOptions
{
    OutputRowNumbers = false,
    OutputColumnHeaders = true,
    // Preserves cell styles as inline CSS
    PreserveStyles = true
});
' Export with inline CSS styles
workBook.ExportToHtml("styled.html", New HtmlExportOptions With {
    .OutputRowNumbers = False,
    .OutputColumnHeaders = True,
    ' Preserves cell styles as inline CSS
    .PreserveStyles = True
})
$vbLabelText   $csharpLabel

我可以僅導出特定的工作表嗎?

是的,您可以僅導出單個工作表:

// Export specific worksheet
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");
sheet.SaveAsHtml("sheet1.html");

// Export multiple specific sheets
foreach (var sheetName in new[] { "Sheet1", "Sheet3" })
{
    workBook.GetWorkSheet(sheetName).SaveAsHtml($"{sheetName}.html");
}
// Export specific worksheet
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");
sheet.SaveAsHtml("sheet1.html");

// Export multiple specific sheets
foreach (var sheetName in new[] { "Sheet1", "Sheet3" })
{
    workBook.GetWorkSheet(sheetName).SaveAsHtml($"{sheetName}.html");
}
' Export specific worksheet
Dim sheet As WorkSheet = workBook.GetWorkSheet("Sheet1")
sheet.SaveAsHtml("sheet1.html")

' Export multiple specific sheets
For Each sheetName As String In {"Sheet1", "Sheet3"}
    workBook.GetWorkSheet(sheetName).SaveAsHtml($"{sheetName}.html")
Next
$vbLabelText   $csharpLabel

IronXL 的實際應用案例是什麼?

IronXL 是一個多功能的 .NET 程式庫,具有廣泛的實際應用,包括:

1. 業務報告:

  • 自動化定期報告,例如銷售摘要和財務報表。
  • 從各種資料源建立自定義儀表板。
  • 導出資料為 Excel 用於利益相關者演示。

2. 資料分析:

3. 庫存管理:

4. 客戶關係管理(CRM):

5. 教育機構:

  • 建立學生成績冊和出勤記錄。
  • 生成考試結果和績效分析。
  • 使用公式自動計算成績。

6. 金融服務:

  • 自動化財務模式、預算和預測。
  • 整合財務資料以進行全面報告。
  • 建立圖表進行視覺分析。

7. 人力資源:

8. 項目管理:

  • 跟踪項目時間表和資源分配。
  • 建立甘特圖和項目管理工具。
  • 使用命名範圍進行公式管理。

9. 電子商務:

  • 將訂單詳情、客戶資訊和銷售資料從電子商務平台導出到 Excel。
  • 分析銷售趨勢、客戶行為和產品績效。

10. 醫療保健:

  • 管理患者記錄和約診安排。
  • 分析醫療資料以提高患者護理。
  • 使用工作表保護保護患者資料

哪些行業從 IronXL 獲益最多?

需要處理大量結構化資料的行業獲益最多:

IronXL 如何處理大規模資料處理?

IronXL 針對效能進行優化,具備以下特點:

  • 大文件的高效記憶體管理
  • 巨大資料集的流處理能力
  • 支持背景處理
  • 多執行緒安全操作

常見的整合場景有哪些?

常見的整合場景有:

如何將 IronXL 授權用於生產用途?

IronXL 是 Iron Software 的企業級程式庫。 它需要授權才能運行。 您可以在這裡使用您的電子信箱下載試用授權。 一旦提交,授權將發送至您的郵箱。 將此授權放置在程式碼開始處,於使用 IronXL 之前:

License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
$vbLabelText   $csharpLabel

有哪些型別的授權可用?

IronXL 提供多種型別的授權

  • Lite 授權:適用於個人開發者
  • Professional 授權:適用於小型團隊
  • Enterprise 授權:適用於大型組織
  • SaaS 授權:適用於基於雲端應用程式
  • OEM 授權:適用於再分發

我該如何應用授權金鑰?

您可以通過多種方式應用授權金鑰

// Method 1: In code
IronXL.License.LicenseKey = "YOUR-LICENSE-KEY";

// Method 2: Using app.config or web.config
// Add to configuration file:
// <appSettings>
//   <add key="IronXL.LicenseKey" value="YOUR-LICENSE-KEY"/>
// </appSettings>

// Method 3: Using environment variable
Environment.SetEnvironmentVariable("IRONXL_LICENSE_KEY", "YOUR-LICENSE-KEY");
// Method 1: In code
IronXL.License.LicenseKey = "YOUR-LICENSE-KEY";

// Method 2: Using app.config or web.config
// Add to configuration file:
// <appSettings>
//   <add key="IronXL.LicenseKey" value="YOUR-LICENSE-KEY"/>
// </appSettings>

// Method 3: Using environment variable
Environment.SetEnvironmentVariable("IRONXL_LICENSE_KEY", "YOUR-LICENSE-KEY");
' Method 1: In code
IronXL.License.LicenseKey = "YOUR-LICENSE-KEY"

' Method 2: Using app.config or web.config
' Add to configuration file:
' <appSettings>
'   <add key="IronXL.LicenseKey" value="YOUR-LICENSE-KEY"/>
' </appSettings>

' Method 3: Using environment variable
Environment.SetEnvironmentVariable("IRONXL_LICENSE_KEY", "YOUR-LICENSE-KEY")
$vbLabelText   $csharpLabel

針對網站應用程式,您也可以在Web.config 中設置授權

試用期結束後會發生什麼?

當試用期結束後:

  • 生成的文件上會出現浮水印
  • 一些功能可能會受限
  • 不允許生產部署

為了繼續使用 IronXL,請購買商業授權。 該團隊為現有客戶提供授權擴展升級

我們從 C# 中的 Excel 文件操作中學到了什麼?

IronXL 是一個強大的 .NET 程式庫,用於建立、讀取和編輯 Excel 文件,它提供了直觀的 API,簡化了 Excel 文件的操作。 它支持多種格式,包括 XLS、XLSX 和 CSV,讓其在各種使用情境中具有多功能性。 IronXL 允許輕鬆操作單元格值、公式和格式,並針對效能進行優化,能有效處理大型文件和複雜的操作。 其記憶體管理確保應用程式的響應性,並且其跨平台相容性讓不同作業系統的開發者能夠獲益。

無論您是在構建網站應用程式桌面軟體還是雲端服務,IronXL 都提供了在 C# 中有效地使用 Excel 文件所需的工具。 有關更多的高級功能,請查看完整的文件並探索豐富的程式碼範例

關鍵要點:

通過查看變更日志里程碑,隨時了解 IronXL 的持續增強功能和最新改進。

常見問題

如何在未安裝 Microsoft Excel 的情況下在 C# 中操作 Excel 文件?

您可以使用 IronXL,一個來自 Iron Software 的 C# 程式庫,來讀取、寫入及操作 Excel 文件,而無需安裝 Microsoft Excel。它支持各種格式,如 XLS、XLSX 和 CSV,並可用於 Web 服務、桌面和控制台應用程式中。

設置一個 Visual Studio 專案以在 C# 中操作 Excel 涉及哪些步驟?

為在 C# 中操作 Excel 設置 Visual Studio 專案,通過 NuGet 套件管理器安裝 IronXL。請在套件管理器控制台中使用命令:dotnet add package IronXL.Excel --version 2024.8.5 將程式庫新增到您的專案中。

我可以使用 C# 在 Excel 文件中進行計算嗎?

是的,使用 IronXL 您可以在 Excel 文件中進行計算。此程式庫支持 Excel 公式,允許您直接在 C# 應用程式中自動化計算。

如何使用 C# 將 Excel 文件轉換為 HTML?

IronXL 提供 ExportToHtml 方法來將 Excel 文件轉換為 HTML。此方法允許自訂選項,確保 HTML 輸出滿足您的要求。

using IronXL 在 C# 中操作 Excel 文件有什麼好處?

IronXL 提供直觀的 API、優化的大型 Excel 文件處理性能,並在各種應用中展示其多樣性。其跨平台相容性和全面的文件進一步增強了其實用性。

我可以使用 IronXL 為 Excel 儲存格應用高級樣式嗎?

是的,使用 IronXL,您可以為 Excel 儲存格應用高級樣式,例如自訂字體、大小、顏色、邊框和對齊方式,通過每個儲存格的 Style 屬性來實現。

IronXL 適合跨平台 Excel 文件操作嗎?

是的,IronXL 被設計為跨平台,相容 Windows、macOS、Linux 和諸如 Docker、Azure 和 AWS 等環境,使其適用於各種部署場景。

如何使用 IronXL 在 C# 中從 Excel 文件讀取儲存格值?

using IronXL,您可以通過 WorkBook.Load 載入 Excel 文件,選擇工作表,並使用其地址存取特定的儲存格值或範圍。

什麼使 IronXL 成為在 C# 中處理 Excel 文件的強大工具?

IronXL 之所以強大,是因為其支持多種格式 (XLS、XLSX、CSV)、公式和樣式功能、加密安全性,以及其能夠在不同操作系統中高效處理大型文件的能力。

Curtis Chau
技術作家

Curtis Chau擁有Carleton大學的電腦科學學士學位,專精於前端開發,擁有Node.js、TypeScript、JavaScript和React的專業知識。Curtis熱衷於建立直觀且美觀的使用者介面,喜愛使用現代框架並建立結構良好、視覺吸引力的手冊。

除了開發,Curtis對物聯網(IoT)有濃厚的興趣,探索創新的方法來整合硬體和軟體。在空閒時間,他喜歡玩遊戲和建立Discord機器人,結合他對技術的熱愛與創造力。

Iron 支援團隊

我們線上24小時,每週5天。
聊天
電子郵件
給我打電話