如何在 C# 中處理 Excel 檔案:圖 1 - 教學課程
IronXL 是一款強大的 C# 程式庫,讓開發人員無需安裝 Microsoft Excel 即可讀取、寫入及處理 Excel 檔案,具備跨平台相容性,並透過直覺的 API 支援 XLS、XLSX、CSV 等格式。
如何在 C# 中處理 Excel 工作簿?
- 建立一個 Visual Studio 專案並新增 IronXL NuGet 套件。
- 建立一個不含互通性的 Excel 檔案。
- 使用 IronXL 為 Excel 檔案新增樣式。
- 從 Excel 讀取數值並進行計算。
- 將 Excel 轉換為 HTML 以便在網頁上使用。
什麼是 IronXL 程式庫?
IronXL程式庫是一個功能強大的 .NET 程式庫,可簡化 Excel 檔案的操作流程。 它具備直觀的 API,可簡化 Excel 文件的處理,並支援 XLS、XLSX 和 CSV 等多種格式。 這種多功能性讓您能輕鬆操作儲存格值、公式及格式設定。 IronXL 經過效能優化,能夠高效處理大型檔案與複雜的資料運算,同時確保記憶體使用效率。 其跨平台相容性,使其在不同作業系統上皆能發揮實用價值。 以下是其主要功能與優勢:
IronXL 的主要功能有哪些?
1.進出口:
- 匯入資料:支援 XLS、XLSX、CSV 及 TSV 格式。
- 匯出資料:可將工作表匯出為 XLS、XLSX、CSV、TSV 及 JSON 格式。
2.資料處理:
- System.Data Integration:將電子表格作為
DataSet和DataTable物件進行操作。 - 公式:支援 Excel 公式,當工作表被編輯時會自動重新計算。
3.樣式和格式:
4.安全性:
- 加密:使用密碼對 XLSX、XLSM 和 XLTX 檔案進行加密與解密。
5.跨平台相容性:
- 支援 .NET Framework、.NET Core、.NET Standard 及 Azure。
- 相容於 Windows、macOS、Linux、Docker 及 AWS。
為何應選擇 IronXL 程式庫而非其他 Excel 函式庫?
- 無需 Microsoft Office:IronXL 無需安裝 Microsoft Office,使其輕量且易於部署。
- 易用性:此 API 直觀且易於使用,讓開發人員能快速將 Excel 功能整合至其應用程式中。
- 效能:IronXL 經過效能優化,可確保快速且高效地處理大型 Excel 檔案。
- 多功能性:適用於廣泛的應用場景,包括網頁、桌面及雲端解決方案。
- 完整文件:提供詳盡的文件與範例,讓開發者更容易上手並找到常見問題的解決方案。
如何開始使用 IronXL?
要在 .NET 專案中使用 IronXL,您需要確保您的開發環境符合以下先決條件:
使用 IronXL 的先決條件是什麼?
- .NET Framework:IronXL 支援 .NET Framework 4.5 及以上版本。
- .NET Core 與 .NET Standard:相容於 .NET Core 2、3、5、6、7、8 及 9。
- 作業系統:支援 Windows、macOS 及 Linux。 相容於 Docker、Azure 及 AWS。
- 無需 Microsoft Office:IronXL 無需 Office 或 Excel 互通功能。
- 程式碼編輯器:任何 C# 程式碼編輯器,例如 Visual Studio。
如何在我的專案中安裝 IronXL?
您可以透過 Visual Studio 中的 NuGet 套件管理器安裝 IronXL,也可以使用套件管理器控制台,透過下列指令安裝:
dotnet add package IronXL.Excel --version 2024.8.5
dotnet add package IronXL.Excel --version 2024.8.5
如何使用 IronXL 建立我的第一個 Excel 檔案?
讓我們建立一個 Visual Studio 專案,並加入 IronXL程式庫,開始處理 Excel 檔案。
如何建立 Visual Studio 專案並加入 IronXL?
開啟 Microsoft Visual Studio,並選擇"建立新專案"以開始操作。
Visual Studio 2022 啟動畫面顯示開啟最近專案、複製儲存庫、開啟專案/解決方案、開啟本機資料夾或建立新專案的選項。
請選擇您偏好的專案範本。為簡化說明,此處我們選用了"主控台應用程式"。
Visual Studio 的"建立新專案"對話方塊顯示了 C# 的控制台應用程式選項,同時提供 .NET Core 和 .NET Framework 版本。
現在請輸入項目名稱和項目地點。
選擇您偏好的 .NET Framework 版本。 我們已選用本機上可用的最新版本。
Visual Studio 專案建立對話方塊顯示了控制台應用程式配置,其中已選擇 .NET 8.0 框架,並提供了頂級語句和 AOT 發布等其他選項。
點擊"建立"按鈕後,專案即會建立並可供使用。 開啟解決方案資源管理器以查看專案文件。
Visual Studio NuGet 套件管理器顯示已安裝 IronXL.Excel 套件,並為名為 WorkingWithIronXL 的 C# 專案選擇了 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
程式碼解釋
- 我們新增 IronXL 命名空間以開始使用該庫。
- 使用
WorkBook.Create()建立 Excel 物件以建立 XLSX 檔案。 - 呼叫
CreateWorkSheet方法在工作簿中建立工作表。 - 使用
workSheet["A1"].Value在儲存格中新增數值。 - 使用
workBook.SaveAs儲存 Excel 文件,並提供檔案名稱。
輸出 Excel 文件
! Excel 電子表格在 A1 單元格中顯示"IronXL 是最好的 Excel 庫"文本,演示如何使用 C# 中的 IronXL 以編程方式創建 Excel 文件。
為何 IronXL 不需要 Interop?
與依賴 Microsoft Excel Interop 的傳統方法不同,IronXL 是一個獨立的 .NET 程式庫,可直接讀取和寫入 Excel 檔案。 這意味著
我可以儲存為哪些檔案格式?
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
如何處理建立檔案時的錯誤?
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
如何使用 IronXL 為 Excel 檔案套用樣式?
現在我們來看看如何為 Excel 儲存格新增樣式。 IronXL 提供全面的樣式設定選項,可協助您建立外觀 Professional 的試算表。
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
程式碼解釋
- 使用
WorkBook.Create建立一個 Excel 檔案。 - 使用
workBook.CreateWorkSheet建立一個工作表。 - 使用
workSheet["A1"].Value在儲存格中新增數值。 - 使用類似
workSheet["A1"].Style.Font.Bold的屬性為儲存格新增樣式。 - 使用
workBook.SaveAs儲存工作簿。
輸出 Excel 文件
! Excel 電子表格在 A1 單元格中顯示紅色斜體文字"This Styled Text with Awesome IronXL library",在 A2 單元格中顯示綠色文字"999999"。
有哪些造型選擇?
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
我可以使用條件格式化嗎?
是的,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)
如何從 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
程式碼解釋
- 使用
WorkBook.Load載入 Excel 檔案。 - 開啟工作簿中的第一個工作表。
- 讀取特定儲存格的值並使用
Console.WriteLine顯示它。 - 遍歷一組儲存格,並PRINT每個值。 PRINT 新行後在 H 欄後換行。
- 計算範圍 F2:F10 內的數值總和並 PRINT 結果。
輸入 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
如何處理空值或 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
有哪些聚合函數可用?
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()
如何將 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
程式碼解釋
- 使用
Load方法載入 Excel 檔案。 - 使用
HtmlExportOptions設定 HTML 轉換選項。 - 使用
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"
}
如何在 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
})
我可以只匯出特定的工作表嗎?
是的,您可以匯出個別工作表:
// 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
IronXL 的實際應用案例有哪些?
IronXL 是一個功能強大的 .NET 程式庫,擁有廣泛的實際應用,包括:
1. 業務報告:
- 自動化生成定期報告,例如銷售摘要和財務報表。
- 從各種資料來源建立自訂儀表板。
- 將資料匯出至 Excel,供向利害關係人進行簡報。
2. 資料分析:
3. 庫存管理:
- 管理產品庫存,包含庫存數量及供應商詳細資訊。
- 生成庫存報告以追蹤趨勢。
- 從供應商處匯入 CSV 資料。
4. 客戶關係管理(CRM):
5. 教育機構:
- 建立學生成績冊與出勤紀錄。
- 生成考試成績與表現分析。
- 使用公式自動計算成績。
6. 金融服務:
- 自動化財務模型、預算與預測。
- 整合財務數據以進行全面性報表編製。
- 建立圖表以進行視覺化分析。
7. 人力資源:
- 管理員工資料,包括薪資與績效評估。
- 生成關於人力資源指標與人口統計的報告。
- 透過密碼加密保護敏感資料。
8. 專案管理:
- 追蹤專案時程與資源分配。
- 建立甘特圖與專案管理工具。
- 使用命名範圍進行公式管理。
9. 電子商務:
- 將電子商務平台上的訂單詳情、客戶資訊和銷售資料匯出到 Excel。
- 分析銷售趨勢、顧客行為和產品績效。
10. 醫療保健:
- 管理病患紀錄與預約時程。
- 分析醫療保健數據以改善病患照護。
- 透過工作表保護功能確保病患資料安全。
哪些產業能從 IronXL 中獲益最多?
處理大量結構化資料的產業將受益最多:
IronXL 如何處理大規模資料處理?
IronXL 透過以下方式進行效能優化:
- 針對大型檔案的高效記憶體管理
- 處理龐大資料集的串流處理能力
- 支援背景處理
- 多執行緒安全操作
常見的整合情境有哪些?
常見的整合情境包括
- 用於檔案上傳/下載的 ASP.NET 網頁應用程式
- Azure Functions 用於雲端處理
- 透過 SQL 資料庫整合實現資料同步
- 用於互動式網頁使用者介面的 Blazor 應用程式
- 微服務的 Docker 容器
如何為 IronXL 取得生產環境使用授權?
IronXL 是 Iron Software 推出的一款 Enterprise 程式庫。 執行時需要授權。 您可由此處使用電子郵件帳號下載試用授權。 提交後,授權憑證將發送至您的電子郵件。 請在使用 IronXL 之前,將此授權條款置於程式碼開頭:
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here";
License.LicenseKey = "your Key Here"
有哪些可用的授權類型?
IronXL 提供多種授權類型:
- Lite License:適用於個人開發者
- Professional License:適用於小型團隊
- 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")
對於 Web 應用程式,您也可以在 Web.config 中設定授權。
試用期屆滿後會發生什麼情況?
試用期屆滿時:
- 生成的檔案上會出現浮水印
- 部分功能可能受限
- 禁止進行生產環境部署
關於在 C# 中處理 Excel 檔案,我們學到了什麼?
IronXL 是一款功能強大的 .NET 程式庫,用於建立、讀取及編輯 Excel 檔案,提供直覺的 API,讓處理 Excel 文件變得更為簡便。 它支援多種格式,包括 XLS、XLSX 和 CSV,使其能靈活應對各種使用情境。 IronXL 可以輕鬆操作單元格值、公式和格式,並針對效能進行了最佳化,能夠有效地處理大型檔案和複雜操作。 其記憶體管理機制確保應用程式反應靈敏,而跨平台相容性使其對使用不同作業系統的開發者而言極具價值。
無論您正在開發網頁應用程式、桌面軟體或雲端服務,IronXL 都能提供在 C# 環境中高效處理 Excel 檔案所需的工具。 如需了解進階功能,請參閱完整文件並探索豐富的程式碼範例。
主要心得:
常見問題解答
如何在未安裝 Microsoft Excel 的情況下以 C# 操作 Excel 文件?
您可以使用 IronXL,這是一個來自 Iron Software 的 C# 函式庫,來讀取、寫入和操作 Excel 文件,而不需要 Microsoft Excel。它支持多種格式,如 XLS、XLSX 和 CSV,並可用於網路服務、桌面和控制台等應用程序。
設置一個 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 輸出符合您的要求。
使用 IronXL 在 C# 中操作 Excel 文件有哪些好處?
IronXL 提供了易於使用的直觀 API,為處理大型 Excel 文件提供了優化的性能,並且在多種應用中具有多功能性。其跨平台兼容性和全面的文檔進一步提高了其實用性。
我可以使用 IronXL 對 Excel 單元格應用高級樣式嗎?
是的,使用 IronXL,您可以對 Excel 單元格應用高級樣式,如自定義字體、大小、顏色、邊框和對齊方式,使用每個單元格的 Style 屬性。
IronXL 是否適合跨平台的 Excel 文件操作?
是的,IronXL 設計為支持跨平台,與 Windows、macOS、Linux 及 Docker、Azure 和 AWS 等環境兼容,使其適合於各種部署場景。
如何在 C# 中使用 IronXL 讀取 Excel 文件中的單元格值?
使用 IronXL,您可以通過加載文件使用 WorkBook.Load,選擇工作表並使用地址訪問特定單元格值或範圍。
IronXL 為何成為在 C# 中處理 Excel 文件的強大工具?
IronXL 強大之處在於其支持多種格式(XLS、XLSX、CSV),公式和樣式功能,安全加密,以及在不同操作系統上高效處理大型文件的能力。


