如何在 C# 中处理 Excel 文件:图 1 - 教程
IronXL 是一个功能强大的 C# 库,它使开发人员无需安装 Microsoft Excel 即可读取、写入和操作 Excel 文件,提供跨平台兼容性,并通过直观的 API 支持 XLS、XLSX、CSV 等格式。
如何在C#中与Excel工作簿进行工作?
- 创建一个Visual Studio项目并添加IronXL NuGet包。
- 创建一个不使用Interop的Excel文件。
- 使用IronXL为Excel文件添加样式。
- 从Excel中读取值并计算。
- 将Excel转换为HTML以用于网络使用。
什么是 IronXL 库?
IronXL 是一个功能强大的 .NET 库,可简化 Excel 文件的操作。 它拥有直观的 API,可简化 Excel 文档的操作,支持 XLS、XLSX 和 CSV 等多种格式。 这种多功能性使得对单元格值、公式和格式进行操作变得轻松便捷。 IronXL 经过性能优化,能够高效处理大型文件和复杂的数据操作,同时确保内存使用效率。 其跨平台兼容性增强了其在不同操作系统中的实用性。 以下是其主要功能和优势:
IronXL 的主要功能有哪些?
-
导入和导出:
- 导入数据:支持 XLS、XLSX、CSV 和 TSV 格式。
- 导出数据:可将工作表导出为 XLS、XLSX、CSV、TSV 和 JSON 格式。
-
数据操作:
- System.Data 集成:将电子表格作为
DataSet和DataTable对象进行处理。 - 公式:支持 Excel 公式,当工作表被编辑时会自动重新计算。
- System.Data 集成:将电子表格作为
-
样式和格式:
-
安全:
- 加密:使用密码对 XLSX、XLSM 和 XLTX 文件进行加密和解密。
- 跨平台兼容性:
为什么我应该选择 IronXL 而不是其他 Excel 库?
- 无需 Microsoft Office:IronXL 无需安装 Microsoft Office,因此体积轻巧且易于部署。
- 易用性:该 API 直观易用,使开发人员能够快速将 Excel 功能集成到其应用程序中。
- 性能:IronXL 经过性能优化,可确保快速高效地处理大型 Excel 文件。
- 多功能性:适用于广泛的应用场景,包括 Web、桌面和基于云的解决方案。
- 详尽的文档:提供丰富的文档和示例,帮助开发者更轻松地入门并解决常见问题。
如何开始使用 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
如何使用 IronXL 创建我的第一个 Excel 文件?
让我们创建一个 Visual Studio 项目并添加 IronXL库,开始处理 Excel 文件。
如何创建 Visual Studio 项目并添加 IronXL?
打开 Microsoft Visual Studio,选择"创建新项目"以开始操作。

请选择您需要的项目模板。为简化操作,此处我们选择了"控制台应用程序"。

现在输入项目的名称和位置。

选择您偏好的.NET Framework版本。 我们已选定本机上可用的最新版本。

点击"创建"按钮后,项目即创建完成并可供使用。 打开解决方案资源管理器以检查项目文件。

现在,让我们按上面所示从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文件

为什么 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 提供了全面的样式选项,用于创建外观专业的电子表格。
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 文件

有哪些造型选择?
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

输出

我可以从单元格中读取哪些数据类型?
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
如何处理空单元格或空值?
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 以供网页使用。 这对于在 Web 应用程序中显示 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。
输入

输出

有哪些 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 Web 应用程序
- 用于云端处理的 Azure Functions
- 支持 SQL 数据库集成以实现数据同步
- 用于交互式 Web 用户界面的 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允许轻松操作单元格值、公式和格式,经过性能优化,能够高效处理大型文件和复杂操作。 其内存管理机制确保应用程序响应迅速,而跨平台兼容性使其对不同操作系统的开发者都极具价值。
无论您是在开发 Web 应用程序、桌面软件还是云服务,IronXL 都能提供在 C# 中高效处理 Excel 文件所需的工具。 如需了解更高级的功能,请查阅完整文档并探索丰富的代码示例。
关键要点:
常见问题解答
如何在没有安装 Microsoft Excel 的情况下在 C# 中操作 Excel 文件?
您可以使用 IronXL,这是一款来自 Iron Software 的 C# 库,用于读取、写入和操作 Excel 文档,而无需 Microsoft Excel。它支持多种格式,如 XLS、XLSX 和 CSV,并可用于如 Web 服务、桌面和控制台等应用。
在 C# 中设置一个 Visual Studio 项目以处理 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 输出符合您的要求。
在 C# 中使用 IronXL 操作 Excel 文件的好处是什么?
IronXL 提供易于使用的直观 API、针对大型 Excel 文件优化的性能以及各种应用的多功能性。其跨平台兼容性和全面的文档使其效用更上一层楼。
我可以使用 IronXL 将高级样式应用于 Excel 单元格吗?
可以,使用 IronXL,您可以将高级样式应用于 Excel 单元格,比如通过每个单元格的样式属性自定义字体、大小、颜色、边框和对齐方式。
IronXL 是否适合跨平台 Excel 文件操作?
是的,IronXL 被设计为跨平台的,兼容 Windows、macOS、Linux 以及 Docker、Azure 和 AWS 等环境,使其成为多种部署方案的理想选择。
我如何在 C# 中使用 IronXL 读取 Excel 文件中的单元格值?
using IronXL,您可以通过加载文件使用 WorkBook.Load,选择工作表,并根据地址访问特定的单元格值或范围来读取 Excel 文件中的单元格值。
是什么使 IronXL 成为处理 C# 中 Excel 文件的强大工具?
IronXL 因其对多种格式(XLS、XLSX、CSV)的支持、公式和样式能力、安全的加密以及在各种操作系统上高效处理大文件的能力而强大。




