使用 IRONXL 通过.NET CLI 安装(推荐用于 CI/CD 流水线) Curtis Chau 已更新:2026年1月19日 下载 IronXL NuGet 下载 DLL 下载 免费试用 LLM副本 LLM副本 将页面复制为 Markdown 格式,用于 LLMs 在 ChatGPT 中打开 向 ChatGPT 咨询此页面 在双子座打开 向 Gemini 询问此页面 在 Grok 中打开 向 Grok 询问此页面 打开困惑 向 Perplexity 询问有关此页面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 复制链接 电子邮件文章 IronXL使开发人员能够使用简洁的 C# 代码在.NET Core应用程序中修改 Excel 单元格,而无需使用 Microsoft Office。它支持单元格操作、范围操作,并可部署在 Windows、Linux 和 macOS 系统上。 为什么选择IronXL进行.NET Core Excel 开发? 在.NET Core中使用 Excel对于现代企业应用程序至关重要,尤其是在云原生和容器化环境中。 IronXL库提供丰富的 Excel 功能,可在各种平台上流畅运行,无需安装 Microsoft Office。 对于自动化报告生成、数据处理管道和 CI/CD 工作流的工程师来说,这项功能尤其有价值。 设想这样一个典型场景:您的团队需要从各种数据源生成月度绩效报告,根据计算结果修改特定单元格,并将此功能部署到跨多个环境的 Docker 容器中。 传统的 Excel 自动化需要在每台服务器上安装 Office,这会造成许可方面的麻烦和部署上的复杂性。 IronXL提供了一个独立的解决方案,可以消除这些障碍,该方案适用于所有运行.NET Core应用程序的地方。 该库擅长从头开始创建电子表格、以编程方式管理工作表以及在无需外部依赖的情况下转换文件格式。 无论您是构建微服务、无服务器函数还是容器化应用程序, IronXL都能自然地集成到现代工作流程中。 为什么选择IronXL进行云原生 Excel 处理? 云环境需要轻量级、灵活的解决方案。 IronXL开箱即用,支持Docker 部署、 Azure Functions和AWS Lambda 。 该库的架构确保在保持高性能的同时最大限度地减少资源消耗,这对于经济高效的云操作至关重要。 无需 Interop 即可使用 Excel ,从而使部署更加简洁高效。 .NET Core Excel 编辑的关键功能 能力 说明 跨平台兼容性 原生支持 Windows、Linux 和 macOS 集装箱式 针对 Docker 和 Kubernetes 部署进行了优化 云原生集成 与无服务器平台完美兼容 无外部依赖 无需 Office 的独立图书馆 性能优化 大规模操作的高效内存使用 如何安装IronXL库 在.NET Core项目中开始使用IronXL只需几分钟。 该库可通过标准软件包管理器获取,并支持所有现代部署方案。 以下是如何将IronXL添加到您的项目中: dotnet add package IronXl.Excel # Or use Package Manager Console in Visual Studio Install-Package IronXl.Excel # For specific version installation (useful for reproducible builds) dotnet add package IronXl.Excel --version 2024.12.0 # Add to your .csproj file for declarative package management # <PackageReference Include="IronXl.Excel" Version="2024.12.0" /> dotnet add package IronXl.Excel # Or use Package Manager Console in Visual Studio Install-Package IronXl.Excel # For specific version installation (useful for reproducible builds) dotnet add package IronXl.Excel --version 2024.12.0 # Add to your .csproj file for declarative package management # <PackageReference Include="IronXl.Excel" Version="2024.12.0" /> SHELL 配置生产环境许可 安装完成后,配置您的许可证密钥以进行生产部署。 IronXL提供灵活的许可选项,适用于不同的部署规模,从单服务器应用程序到企业级解决方案。 对于 Web 应用程序,您可以在 web.config 中配置许可证以进行集中管理。 随着需求的增长,请考虑扩展应用程序的许可和升级选项。 改进IronXL在容器环境中的性能 在部署到容器时,请考虑以下符合Docker 设置最佳实践的优化策略: # Dockerfile example for IronXL applications FROM mcr.microsoft.com/dotnet/runtime:6.0-alpine AS base WORKDIR /app # Install required dependencies for Excel processing RUN apk add --no-cache \ icu-libs \ krb5-libs \ libgcc \ libintl \ libssl1.1 \ libstdc++ \ zlib FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build WORKDIR /src COPY ["YourProject.csproj", "./"] RUN dotnet restore "YourProject.csproj" COPY . . RUN dotnet build "YourProject.csproj" -c Release -o /app/build FROM build AS publish RUN dotnet publish "YourProject.csproj" -c Release -o /app/publish FROM base AS final WORKDIR /app COPY --from=publish /app/publish . ENTRYPOINT ["dotnet", "YourProject.dll"] 在.NET Core中快速修改 Excel 单元格 以下是一个演示核心功能的实际示例。 这段代码演示了如何加载现有的 Excel 文件并修改特定单元格: using IronXL; using System; class QuickStartExample { static void Main() { // Load existing Excel file - supports XLSX, XLS, XLSM, XLTX WorkBook workBook = WorkBook.Load("sales_report.xlsx"); // Access the default worksheet (usually first sheet) WorkSheet sheet = workBook.DefaultWorkSheet; // Modify individual cells with different data types sheet["A1"].Value = "Q4 Sales Report"; // String value sheet["B2"].Value = DateTime.Now; // Date value sheet["C2"].Value = 158750.50; // Numeric value // Apply formulas for calculations sheet["D2"].Formula = "=C2*1.15"; // 15% markup sheet["E2"].Formula = "=D2-C2"; // Profit calculation // Bulk update a range of cells sheet["A5:A15"].Value = "Updated by Automation"; // Style the header row sheet["A1:E1"].Style.Font.Bold = true; sheet["A1:E1"].Style.BackgroundColor = "#1F4788"; sheet["A1:E1"].Style.Font.Color = "#FFFFFF"; // Save the modified workbook workBook.SaveAs("sales_report_updated.xlsx"); Console.WriteLine("Excel file updated successfully!"); } } using IronXL; using System; class QuickStartExample { static void Main() { // Load existing Excel file - supports XLSX, XLS, XLSM, XLTX WorkBook workBook = WorkBook.Load("sales_report.xlsx"); // Access the default worksheet (usually first sheet) WorkSheet sheet = workBook.DefaultWorkSheet; // Modify individual cells with different data types sheet["A1"].Value = "Q4 Sales Report"; // String value sheet["B2"].Value = DateTime.Now; // Date value sheet["C2"].Value = 158750.50; // Numeric value // Apply formulas for calculations sheet["D2"].Formula = "=C2*1.15"; // 15% markup sheet["E2"].Formula = "=D2-C2"; // Profit calculation // Bulk update a range of cells sheet["A5:A15"].Value = "Updated by Automation"; // Style the header row sheet["A1:E1"].Style.Font.Bold = true; sheet["A1:E1"].Style.BackgroundColor = "#1F4788"; sheet["A1:E1"].Style.Font.Color = "#FFFFFF"; // Save the modified workbook workBook.SaveAs("sales_report_updated.xlsx"); Console.WriteLine("Excel file updated successfully!"); } } $vbLabelText $csharpLabel 为什么这种模式非常适合自动化? 这种模式非常适合自动化工作流程,因为它具有确定性,不需要用户交互。 您可以安排此代码在容器中运行,通过事件或基于时间的计划触发,使其成为自动化场景的理想选择。 能够以编程方式打开和编辑Excel 工作表,可以实现有效的自动化。 启动一个.NET Core Excel 编辑项目 构建可靠的 Excel 编辑解决方案需要正确的项目设置。让我们创建一个完整的示例,演示生产部署的最佳实践,包括错误处理和日志记录: using IronXL; using System; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Logging; public class ExcelProcessor { private readonly ILogger<ExcelProcessor> _logger; private readonly string _workingDirectory; public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory) { _logger = logger; _workingDirectory = workingDirectory; } public async Task ProcessExcelFileAsync(string fileName) { try { var filePath = Path.Combine(_workingDirectory, fileName); // Validate file exists if (!File.Exists(filePath)) { _logger.LogError($"File not found: {filePath}"); throw new FileNotFoundException("Excel file not found", fileName); } // Load workbook with error handling _logger.LogInformation($"Loading Excel file: {fileName}"); WorkBook workBook = WorkBook.Load(filePath); // Process each worksheet foreach (var worksheet in workBook.WorkSheets) { _logger.LogInformation($"Processing worksheet: {worksheet.Name}"); await ProcessWorksheetAsync(worksheet); } // Save with timestamp for version control var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx"; var outputPath = Path.Combine(_workingDirectory, "output", outputName); // Ensure output directory exists Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); workBook.SaveAs(outputPath); _logger.LogInformation($"Saved processed file: {outputName}"); } catch (Exception ex) { _logger.LogError(ex, $"Error processing Excel file: {fileName}"); throw; } } private async Task ProcessWorksheetAsync(WorkSheet worksheet) { // Example: Update timestamp in specific cell var timestampCell = worksheet["A1"]; if (timestampCell.StringValue == "Last Updated:") { worksheet["B1"].Value = DateTime.Now; worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss"; } // Example: Process data rows asynchronously await Task.Run(() => { for (int row = 2; row <= worksheet.RowCount; row++) { // Skip empty rows if (worksheet[$"A{row}"].IsEmpty) continue; // Apply business logic var quantity = worksheet[$"B{row}"].IntValue; var price = worksheet[$"C{row}"].DoubleValue; worksheet[$"D{row}"].Value = quantity * price; worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation } }); } } using IronXL; using System; using System.IO; using System.Threading.Tasks; using Microsoft.Extensions.Logging; public class ExcelProcessor { private readonly ILogger<ExcelProcessor> _logger; private readonly string _workingDirectory; public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory) { _logger = logger; _workingDirectory = workingDirectory; } public async Task ProcessExcelFileAsync(string fileName) { try { var filePath = Path.Combine(_workingDirectory, fileName); // Validate file exists if (!File.Exists(filePath)) { _logger.LogError($"File not found: {filePath}"); throw new FileNotFoundException("Excel file not found", fileName); } // Load workbook with error handling _logger.LogInformation($"Loading Excel file: {fileName}"); WorkBook workBook = WorkBook.Load(filePath); // Process each worksheet foreach (var worksheet in workBook.WorkSheets) { _logger.LogInformation($"Processing worksheet: {worksheet.Name}"); await ProcessWorksheetAsync(worksheet); } // Save with timestamp for version control var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx"; var outputPath = Path.Combine(_workingDirectory, "output", outputName); // Ensure output directory exists Directory.CreateDirectory(Path.GetDirectoryName(outputPath)); workBook.SaveAs(outputPath); _logger.LogInformation($"Saved processed file: {outputName}"); } catch (Exception ex) { _logger.LogError(ex, $"Error processing Excel file: {fileName}"); throw; } } private async Task ProcessWorksheetAsync(WorkSheet worksheet) { // Example: Update timestamp in specific cell var timestampCell = worksheet["A1"]; if (timestampCell.StringValue == "Last Updated:") { worksheet["B1"].Value = DateTime.Now; worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss"; } // Example: Process data rows asynchronously await Task.Run(() => { for (int row = 2; row <= worksheet.RowCount; row++) { // Skip empty rows if (worksheet[$"A{row}"].IsEmpty) continue; // Apply business logic var quantity = worksheet[$"B{row}"].IntValue; var price = worksheet[$"C{row}"].DoubleValue; worksheet[$"D{row}"].Value = quantity * price; worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation } }); } } $vbLabelText $csharpLabel 错误处理的最佳实践 可靠的错误处理对于生产环境部署至关重要。 上述示例演示了日志集成和正确的异常处理,这对于调试容器化环境中的问题至关重要,因为在容器化环境中您可能无法直接访问运行时。请考虑实施安全措施并检查您的使用场景下的文件大小限制。 编辑特定单元格值 让我们来探讨修改单元格值的不同技术,从简单的更新到复杂的数据转换。 IronXL提供直观的方法将值写入 Excel 单元格,同时支持各种数据类型和格式。 您还可以根据需要复制单元格并清除单元格内容。 using IronXL; using System; using System.Linq; using System.Collections.Generic; public class CellEditingExamples { public static void DemonstrateVariousCellEdits() { WorkBook workBook = WorkBook.Load("data.xlsx"); WorkSheet sheet = workBook.DefaultWorkSheet; // 1. Simple value assignment sheet["A1"].Value = "Product Name"; sheet["B1"].Value = 99.99; sheet["C1"].Value = true; sheet["D1"].Value = DateTime.Now; // 2. Using cell references with variables int rowIndex = 5; string columnLetter = "E"; sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference"; // 3. Setting values with specific formatting sheet["F1"].Value = 0.175; sheet["F1"].FormatString = "0.00%"; // Display as 17.50% // 4. Currency formatting sheet["G1"].Value = 1234.56; sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56 // 5. Date formatting variations var dateCell = sheet["H1"]; dateCell.Value = DateTime.Now; dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024" // 6. Setting hyperlinks sheet["I1"].Value = "Visit Documentation"; sheet["I1"].Hyperlink = "___PROTECTED_URL_54___"; // 7. Applying conditional formatting foreach (var cell in sheet["J1:J10"]) { cell.Value = new Random().Next(0, 100); if (cell.IntValue > 50) { cell.Style.BackgroundColor = "#90EE90"; // Light green for high values } else { cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values } } // 8. Working with formulas sheet["K1"].Formula = "=SUM(B1:B10)"; sheet["K2"].Formula = "=AVERAGE(B1:B10)"; sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")"; workBook.SaveAs("data_edited.xlsx"); } } using IronXL; using System; using System.Linq; using System.Collections.Generic; public class CellEditingExamples { public static void DemonstrateVariousCellEdits() { WorkBook workBook = WorkBook.Load("data.xlsx"); WorkSheet sheet = workBook.DefaultWorkSheet; // 1. Simple value assignment sheet["A1"].Value = "Product Name"; sheet["B1"].Value = 99.99; sheet["C1"].Value = true; sheet["D1"].Value = DateTime.Now; // 2. Using cell references with variables int rowIndex = 5; string columnLetter = "E"; sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference"; // 3. Setting values with specific formatting sheet["F1"].Value = 0.175; sheet["F1"].FormatString = "0.00%"; // Display as 17.50% // 4. Currency formatting sheet["G1"].Value = 1234.56; sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56 // 5. Date formatting variations var dateCell = sheet["H1"]; dateCell.Value = DateTime.Now; dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024" // 6. Setting hyperlinks sheet["I1"].Value = "Visit Documentation"; sheet["I1"].Hyperlink = "___PROTECTED_URL_54___"; // 7. Applying conditional formatting foreach (var cell in sheet["J1:J10"]) { cell.Value = new Random().Next(0, 100); if (cell.IntValue > 50) { cell.Style.BackgroundColor = "#90EE90"; // Light green for high values } else { cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values } } // 8. Working with formulas sheet["K1"].Formula = "=SUM(B1:B10)"; sheet["K2"].Formula = "=AVERAGE(B1:B10)"; sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")"; workBook.SaveAs("data_edited.xlsx"); } } $vbLabelText $csharpLabel 高效处理不同数据类型 IronXL会自动检测和转换数据类型,但显式格式化可确保正确显示。 该库支持设置货币、百分比、日期和自定义模式的单元格数据格式。 您可以探索Excel 数字格式,了解更多高级格式设置选项。 此外,您还可以自定义单元格字体和大小,应用背景图案和颜色,以及配置单元格边框和对齐方式。 为多个单元格赋值 批量操作对于提高 Excel 的处理效率至关重要。 IronXL提供有效的范围选择功能,可以轻松同时更新多个单元格。 您还可以根据需要添加行和列、插入新行和列以及合并单元格: using IronXL; using System; using System.Diagnostics; public class BulkCellOperations { public static void PerformBulkUpdates() { var stopwatch = Stopwatch.StartNew(); WorkBook workBook = WorkBook.Load("inventory.xlsx"); WorkSheet sheet = workBook.DefaultWorkSheet; // Method 1: Update entire column sheet["A:A"].Value = "Updated"; Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms"); // Method 2: Update specific range sheet["B2:B100"].Value = DateTime.Now.ToShortDateString(); // Method 3: Update entire row sheet["1:1"].Style.Font.Bold = true; sheet["1:1"].Style.BackgroundColor = "#333333"; sheet["1:1"].Style.Font.Color = "#FFFFFF"; // Method 4: Update rectangular range sheet["C2:E50"].Formula = "=ROW()*COLUMN()"; // Method 5: Update non-contiguous ranges efficiently var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" }; foreach (var range in ranges) { sheet[range].Value = "Batch Update"; sheet[range].Style.BottomBorder.Type = BorderType.Double; } // Method 6: Conditional bulk updates var dataRange = sheet["K1:K100"]; foreach (var cell in dataRange) { // Generate test data cell.Value = new Random().Next(1, 1000); // Apply conditional formatting based on value if (cell.IntValue > 750) { cell.Style.BackgroundColor = "#00FF00"; // Green for high values cell.Style.Font.Bold = true; } else if (cell.IntValue < 250) { cell.Style.BackgroundColor = "#FF0000"; // Red for low values cell.Style.Font.Color = "#FFFFFF"; } } stopwatch.Stop(); Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms"); workBook.SaveAs("inventory_bulk_updated.xlsx"); } } using IronXL; using System; using System.Diagnostics; public class BulkCellOperations { public static void PerformBulkUpdates() { var stopwatch = Stopwatch.StartNew(); WorkBook workBook = WorkBook.Load("inventory.xlsx"); WorkSheet sheet = workBook.DefaultWorkSheet; // Method 1: Update entire column sheet["A:A"].Value = "Updated"; Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms"); // Method 2: Update specific range sheet["B2:B100"].Value = DateTime.Now.ToShortDateString(); // Method 3: Update entire row sheet["1:1"].Style.Font.Bold = true; sheet["1:1"].Style.BackgroundColor = "#333333"; sheet["1:1"].Style.Font.Color = "#FFFFFF"; // Method 4: Update rectangular range sheet["C2:E50"].Formula = "=ROW()*COLUMN()"; // Method 5: Update non-contiguous ranges efficiently var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" }; foreach (var range in ranges) { sheet[range].Value = "Batch Update"; sheet[range].Style.BottomBorder.Type = BorderType.Double; } // Method 6: Conditional bulk updates var dataRange = sheet["K1:K100"]; foreach (var cell in dataRange) { // Generate test data cell.Value = new Random().Next(1, 1000); // Apply conditional formatting based on value if (cell.IntValue > 750) { cell.Style.BackgroundColor = "#00FF00"; // Green for high values cell.Style.Font.Bold = true; } else if (cell.IntValue < 250) { cell.Style.BackgroundColor = "#FF0000"; // Red for low values cell.Style.Font.Color = "#FFFFFF"; } } stopwatch.Stop(); Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms"); workBook.SaveAs("inventory_bulk_updated.xlsx"); } } $vbLabelText $csharpLabel 靶场作业效率 范围操作以单个命令的形式执行,而不是遍历单个单元格,从而显著提高性能。 在处理大型数据集或在资源受限的容器环境中运行时,这种效率至关重要。 通过选择和操作范围,可以用最少的代码实现有效的数据转换。 您还可以对单元格区域进行排序、修剪单元格区域以及合并多个区域。 常见的范围选择模式 图案 句法 说明 列范围 "A:A" 选择 A 列的整个位置 行范围 1:1 选择整行 1 矩形范围 "A1:C3" 选择一个 3x3 的方块 命名范围 创建和使用命名范围 为了清晰起见 动态范围 以编程方式构建范围字符串 灵活选择 使用用户输入编辑单元格 当与用户输入或外部数据源结合使用时,交互式 Excel 编辑功能才能发挥最大效用。 这种方法对于构建接受参数并生成自定义报告的 API 非常有价值。 您可能需要从各种来源导入 Excel 数据或将其导出为不同的格式: using IronXL; using System; using System.Collections.Generic; using System.Threading.Tasks; public class InteractiveExcelEditor { public class EditRequest { public string FileName { get; set; } public string WorksheetName { get; set; } public Dictionary<string, object> CellUpdates { get; set; } public List<RangeUpdate> RangeUpdates { get; set; } } public class RangeUpdate { public string Range { get; set; } public object Value { get; set; } public CellStyle Style { get; set; } } public class CellStyle { public string BackgroundColor { get; set; } public bool Bold { get; set; } public string NumberFormat { get; set; } } public async Task<string> ProcessEditRequestAsync(EditRequest request) { try { // Load workbook WorkBook workBook = WorkBook.Load(request.FileName); WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName) ? workBook.DefaultWorkSheet : workBook.GetWorkSheet(request.WorksheetName); // Process individual cell updates if (request.CellUpdates != null) { foreach (var update in request.CellUpdates) { var cell = sheet[update.Key]; cell.Value = update.Value; // Auto-detect and apply appropriate formatting if (update.Value is decimal || update.Value is double) { cell.FormatString = "#,##0.00"; } else if (update.Value is DateTime) { cell.FormatString = "yyyy-MM-dd"; } } } // Process range updates if (request.RangeUpdates != null) { foreach (var rangeUpdate in request.RangeUpdates) { var range = sheet[rangeUpdate.Range]; range.Value = rangeUpdate.Value; // Apply styling if provided if (rangeUpdate.Style != null) { if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor)) range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor; if (rangeUpdate.Style.Bold) range.Style.Font.Bold = true; if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat)) range.FormatString = rangeUpdate.Style.NumberFormat; } } } // Generate unique output filename string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}"; workBook.SaveAs(outputFile); return outputFile; } catch (Exception ex) { throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex); } } // Example REST API endpoint implementation public static async Task<string> HandleApiRequest(string jsonRequest) { var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest); var editor = new InteractiveExcelEditor(); return await editor.ProcessEditRequestAsync(request); } } using IronXL; using System; using System.Collections.Generic; using System.Threading.Tasks; public class InteractiveExcelEditor { public class EditRequest { public string FileName { get; set; } public string WorksheetName { get; set; } public Dictionary<string, object> CellUpdates { get; set; } public List<RangeUpdate> RangeUpdates { get; set; } } public class RangeUpdate { public string Range { get; set; } public object Value { get; set; } public CellStyle Style { get; set; } } public class CellStyle { public string BackgroundColor { get; set; } public bool Bold { get; set; } public string NumberFormat { get; set; } } public async Task<string> ProcessEditRequestAsync(EditRequest request) { try { // Load workbook WorkBook workBook = WorkBook.Load(request.FileName); WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName) ? workBook.DefaultWorkSheet : workBook.GetWorkSheet(request.WorksheetName); // Process individual cell updates if (request.CellUpdates != null) { foreach (var update in request.CellUpdates) { var cell = sheet[update.Key]; cell.Value = update.Value; // Auto-detect and apply appropriate formatting if (update.Value is decimal || update.Value is double) { cell.FormatString = "#,##0.00"; } else if (update.Value is DateTime) { cell.FormatString = "yyyy-MM-dd"; } } } // Process range updates if (request.RangeUpdates != null) { foreach (var rangeUpdate in request.RangeUpdates) { var range = sheet[rangeUpdate.Range]; range.Value = rangeUpdate.Value; // Apply styling if provided if (rangeUpdate.Style != null) { if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor)) range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor; if (rangeUpdate.Style.Bold) range.Style.Font.Bold = true; if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat)) range.FormatString = rangeUpdate.Style.NumberFormat; } } } // Generate unique output filename string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}"; workBook.SaveAs(outputFile); return outputFile; } catch (Exception ex) { throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex); } } // Example REST API endpoint implementation public static async Task<string> HandleApiRequest(string jsonRequest) { var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest); var editor = new InteractiveExcelEditor(); return await editor.ProcessEditRequestAsync(request); } } $vbLabelText $csharpLabel 将 Excel 编辑功能与 CI/CD 流水线集成 对于 DevOps 场景,将 Excel 处理集成到您的构建和部署管道中。 您可以在ASP.NET应用程序中读取 Excel 文件,或者根据需要处理.NET Excel 文件: # Example GitHub Actions workflow name: Process Excel Reports on: schedule: - cron: '0 2 * * *' # Run daily at 2 AM workflow_dispatch: jobs: process-excel: runs-on: ubuntu-latest container: image: mcr.microsoft.com/dotnet/sdk:6.0 steps: - uses: actions/checkout@v2 - name: Restore dependencies run: dotnet restore - name: Build run: dotnet build --configuration Release - name: Process Excel files run: | dotnet run -- \ --input-dir ./data/input \ --output-dir ./data/output \ --operation bulk-update - name: Upload processed files uses: actions/upload-artifact@v2 with: name: processed-excel-files path: ./data/output/*.xlsx # Example GitHub Actions workflow name: Process Excel Reports on: schedule: - cron: '0 2 * * *' # Run daily at 2 AM workflow_dispatch: jobs: process-excel: runs-on: ubuntu-latest container: image: mcr.microsoft.com/dotnet/sdk:6.0 steps: - uses: actions/checkout@v2 - name: Restore dependencies run: dotnet restore - name: Build run: dotnet build --configuration Release - name: Process Excel files run: | dotnet run -- \ --input-dir ./data/input \ --output-dir ./data/output \ --operation bulk-update - name: Upload processed files uses: actions/upload-artifact@v2 with: name: processed-excel-files path: ./data/output/*.xlsx YAML 更多 Excel 自动化资源 要扩展您的 Excel 自动化功能,请探索以下专业资源: 探索更多高级功能 IronXL除了基本的细胞编辑功能外,还提供更广泛的功能: -在Blazor应用程序中使用 Excel进行基于 Web 的 Excel 处理 -无需 Interop 即可进行 Excel 操作,实现更简洁的部署 从头开始使用.NET创建 Excel 文件 用于数据库集成的Excel 到 SQL 转换 -使用.NET MAUI上的 Excel开发跨平台移动应用 改进Excel处理工作流程 请考虑以下高级技术: -在工作表中添加图片,以生成更丰富的报告。 -创建冻结窗格,以便更好地导航 -应用条件格式来突出显示模式 -实现Excel公式进行动态计算 -为单元格添加注释以作文档说明 Excel编辑快速参考指南 以下是常见Excel编辑操作的综合参考: 手术 代码示例 使用案例 单细胞编辑 sheet["A1"].Value = "New Value" 更新特定数据点 范围编辑 sheet["A1:C10"].Value = "Bulk Update" 批量更新以提高效率 配方应用 sheet["D1"].Formula = "=SUM(A1:C1)" 动态计算 条件格式 根据数值应用颜色 可视化数据分析 日期格式 cell.FormatString = "yyyy-MM-dd" 日期显示一致 货币格式 cell.FormatString = "$#,##0.00" 财务报告 合并单元格 sheet["A1:C1"].Merge() 创建标题和页眉 自动调整列宽 sheet.AutoSizeColumn(0) 提高可读性 本指南全面演示了IronXL如何简化.NET Core环境中的 Excel 自动化。 无论您是构建微服务、部署到容器还是创建无服务器函数, IronXL都能提供高效处理 Excel 所需的工具,而无需外部依赖项。 立即开始在您的 DevOps 工作流程中实施这些模式,以简化报告生成和数据处理任务。 常见问题解答 使用 Excel 在 .NET Core 应用程序中的目的是什么? Excel 在 .NET Core 应用程序中用于高效的数据管理和操作。IronXL 允许开发者使用 C# 以编程方式加载、编辑和保存 Excel 文件,从而提高生产力和数据处理能力。 如何在 .NET Core 项目中安装 Excel 库? 您可以使用以下命令通过 NuGet 包管理器在 .NET Core 项目中安装 IronXL 库:dotnet add package IronXl.Excel。或者,您可以直接从 IronXL 网站下载 DLL 文件。 在 .NET Core 中加载 Excel 文件的步骤是什么? 要在 .NET Core 中使用 IronXL 加载 Excel 文件,请使用 WorkBook.Load 方法。例如,WorkBook wb = WorkBook.Load("sample.xlsx"); 将加载名为 'sample.xlsx' 的 Excel 工作簿。 我可以在 .NET Core 中编辑 Excel 表格的一系列单元格吗? 是的,使用 IronXL,您可以同时编辑 Excel 表格中的一系列单元格。使用语法 ws["A1:A9"].Value = "new value"; 将一个值分配给多个单元格,其中 ws 是一个 WorkSheet 对象。 在 .NET Core 中编辑 Excel 文件时如何处理用户输入? IronXL 允许通过控制台或用户界面捕获用户输入,然后可以用来定义 Excel 电子表格中更新的单元格范围和值。 在 .NET Core 中用于 Excel 操作的编程语言是什么? 使用 C# 可以在 .NET Core 应用程序中以编程方式使用 IronXL 库操作 Excel 文件。 是否有使用 .NET Core 处理 Excel 文件的教程? 是的,可以使用 C# 和 IronXL 阅读和操作 Excel 文件的全面教程。额外资源和示例项目可以在 IronXL 网站上找到。 在 .NET Core 中使用 Excel 库的兼容性要求是什么? IronXL 支持.NET Core 的多个版本。有关详细的兼容性信息,请参阅 IronXL 网站上的文档。 在哪里可以访问 Excel 库的 API 文档? IronXL 的 API 文档可在线查看,提供所有命名空间、方法和功能的详情。请访问 IronXL 网站以获取此资源。 Curtis Chau 立即与工程团队聊天 技术作家 Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。 相关文章 已更新2026年3月1日 在.NET C# 中下载 Excel 文件:将数据导出为 XLSX、CSV 等格式 使用 C# 和IronXL在ASP.NET Core中下载 Excel 文件。从 MVC 控制器导出数据到 XLSX、CSV 和 XML 格式,并返回 MemoryStream 和 File() 函数。包含代码示例。 阅读更多 已更新2026年3月1日 如何在Blazor中使用IronXL导出 Excel 文件 学习如何使用IronXL在Blazor Server 应用程序中将数据导出到 Excel。本指南涵盖项目设置、服务设计、条件格式设置、多工作表报表和错误处理,并提供完整的 C# 代码示例。 阅读更多 已更新2026年2月27日 如何在 C# 中读取 Excel 文件而不是使用 StreamReader 了解为什么 StreamReader 无法读取 Excel 文件,以及如何在 C# .NET中使用IronXL从磁盘或内存流加载 XLSX 和 XLS 工作簿。 阅读更多 在 C# 中生成 Excel 文件
已更新2026年3月1日 在.NET C# 中下载 Excel 文件:将数据导出为 XLSX、CSV 等格式 使用 C# 和IronXL在ASP.NET Core中下载 Excel 文件。从 MVC 控制器导出数据到 XLSX、CSV 和 XML 格式,并返回 MemoryStream 和 File() 函数。包含代码示例。 阅读更多
已更新2026年3月1日 如何在Blazor中使用IronXL导出 Excel 文件 学习如何使用IronXL在Blazor Server 应用程序中将数据导出到 Excel。本指南涵盖项目设置、服务设计、条件格式设置、多工作表报表和错误处理,并提供完整的 C# 代码示例。 阅读更多
已更新2026年2月27日 如何在 C# 中读取 Excel 文件而不是使用 StreamReader 了解为什么 StreamReader 无法读取 Excel 文件,以及如何在 C# .NET中使用IronXL从磁盘或内存流加载 XLSX 和 XLS 工作簿。 阅读更多