IRONSOFTWAREHOME
USING IRONXL

透過 .NET CLI 安裝(建議用於 CI/CD 管線)

Curtis Chau
Curtis Chau
Updated: 2026年6月18日

IronXL允許開發者使用簡單的C#程式碼在.NET Core應用程式中修改Excel單元格,無需Microsoft Office。它支持單元格操作、範圍操作,並可部署於Windows、Linux和macOS。

為什麼選擇使用IronXL進行.NET Core Excel開發?

.NET Core中處理Excel對於現代企業應用程式尤為重要,尤其是在以雲為基礎和容器化的環境中。 IronXL程式庫提供豐富的Excel功能,跨平台運行順暢,無需安裝Microsoft Office。 此功能對於自動化報告生成的DevOps工程師、資料處理管道和CI/CD工作流程特別有價值。

考慮一個典型場景:您的團隊需要從各種資料源生成月度性能報告,根據計算修改特定單元格,並在多個環境的Docker容器中部署這一功能。 傳統的Excel自動化需要在每個伺服器上安裝Office,導致授權問題和部署複雜性。 IronXL提供了一個自包含的解決方案,消除了這些障礙,並可在您所有的.NET Core應用程式運行的地方工作。

該程式庫擅長從頭建立電子表格、程式化管理工作表,以及在文件格式之間進行轉換,無需外部依賴。 無論您是在構建微服務、無伺服器函式還是容器化應用程式,IronXL可自然整合到現代DevOps工作流程中。

為什麼選擇IronXL進行雲原生Excel處理?

雲環境需要輕量靈活的解決方案。 IronXL提供支持Docker部署Azure FunctionsAWS Lambda的開箱即用功能。 該程式庫的架構確保了資源消耗最小化,同時保持高性能,這對於雲運營的成本效率至關重要。 您可以在不使用Interop的情況下使用Excel,使得部署更簡潔高效。

適用於.NET Core Excel編輯的關鍵功能

功能描述
跨平台相容性原生支持Windows、Linux和macOS
容器就緒針對Docker和Kubernetes部署進行了優化
雲原生整合在無伺服器平台上運行順暢
無外部依賴無需Office要求的自包含程式庫
性能優化對大規模操作進行高效的記憶體使用

如何安裝IronXL程式庫

在您的.NET Core專案中使用IronXL僅需幾分鐘。 該程式庫可通過標準的包管理器獲得,並支持所有現代部署場景。 這是將IronXL新增到您的專案中的方法:

dotnet add package IronXL.Excel

或在Visual Studio的Package Manager Console中使用

PM > Install-Package IronXL.Excel

針對特定版本安裝(對於可重現性構建很有用)

dotnet add package IronXL.Excel --version 2024.12.0

或者,新增到您的.csproj文件以進行聲明式包管理

<PackageReference Include="IronXL.Excel" Version="2024.12.0" />
Text

為生產配置授權

安裝後,請配置您的授權金鑰以進行生產部署。 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"]
Text

快速修改.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!");
    }
}

為什麼這種模式適合自動化?

這種模式在自動化工作流程中表現完美,因為它是確定性的,不需要使用者交互。 您可以將此程式碼安排在容器中運行,由事件或基於時間的計劃觸發,使其非常適合DevOps自動化場景。 能夠打開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
            }
        });
    }
}

錯誤處理的最佳實踐

可靠的錯誤處理對生產部署至關重要。 上述例子展示了日誌整合和適當的異常處理,這對於除錯可能無法直接存取運行時的容器環境中的問題至關重要。考慮實施安全措施並檢查您的使用案例的文件大小限制

編輯特定單元格的值

讓我們探索不同的技術來修改單元格值,從簡單的更新到複雜的資料轉換。 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");
    }
}

有效處理不同的資料型別

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");
    }
}

範圍操作的效率

範圍操作以單一命令執行,而不是逐個遍歷單元格,顯著提高了性能。 在處理大型資料集或資源受限的容器環境中,這種效率尤為重要。 能夠選擇和操作範圍使得資料轉換變得有效,所需程式碼最少。 您還可以排序單元格範圍修剪單元格範圍,並組合多個範圍

常用範圍選擇模式

模式語法描述
列範圍"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);
    }
}

將Excel編輯整合到CI/CD流水線

對於DevOps場景,將Excel處理整合到您的構建和部署流水線中。 您可以在ASP.NET應用程式中讀取Excel文件,或在需要時處理VB.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
Text

更多Excel自動化資源

要擴展您的Excel自動化能力,請探索這些專門資源:

探索高級功能

IronXL提供超越基本單元格編輯的豐富功能:

提升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工作流程中實施這些模式,以簡化報告生成和資料處理任務。

Curtis Chau
技術作家

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

...
閱讀更多

相關文章

Key in blue circle

立即免費取得 30 天試用金鑰

Your trial license will be sent to your email address

無任何限制。100% 解鎖。無需信用卡。

bullet_checked無需信用卡或建立帳號無任何限制。100% 解鎖。無需信用卡。
  • Logo Aetna
  • Logo NASA
  • Logo GE
  • Logo Porsche
  • Logo USDA
  • Logo Qatar
Join Millions of Engineers who’ve tried IronPDF
預約您的免費即時演示
Booking Badge

全球數百萬工程師的信賴

Iron Software的客戶標誌
獲得無義務諮詢
填寫以下表格或電郵sales@ironsoftware.com
您的資料將始終保密。
全球數百萬工程師的信賴
Iron Software的客戶標誌
立即獲取您的30天試用金鑰
無需信用卡或帳戶建立