跳過到頁腳內容
使用 IRONXL

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

IronXL 讓開發人員能夠使用簡潔的 C# 程式碼在 .NET Core 應用程式中修改 Excel 儲存格,而無需使用 Microsoft Office。它支援單元格操作、範圍操作,並可部署在 Windows、Linux 和 macOS 系統上。

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

在 .NET Core 中使用 Excel對於現代企業應用程式至關重要,尤其是在雲端原生和容器化環境中。 IronXL 庫提供豐富的 Excel 功能,可在各種平台上流暢運行,無需安裝 Microsoft Office。 對於需要自動化報告產生、資料處理管道和 CI/CD 工作流程的DevOps工程師來說,這項功能尤其有價值。

設想這樣一個典型場景:您的團隊需要從各種資料來源產生每月績效報告,根據計算結果修改特定單元格,並將此功能部署到跨多個環境的 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

# 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!");
    }
}
Imports IronXL
Imports System

Class QuickStartExample
    Shared Sub Main()
        ' Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
        Dim workBook As WorkBook = WorkBook.Load("sales_report.xlsx")

        ' Access the default worksheet (usually first sheet)
        Dim sheet As WorkSheet = 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.5           ' 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!")
    End Sub
End Class
$vbLabelText   $csharpLabel

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

這種模式非常適合自動化工作流程,因為它具有確定性,不需要使用者互動。 您可以安排此程式碼在容器中運行,並根據事件或基於時間的計劃觸發,使其成為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
            }
        });
    }
}
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
            }
        });
    }
}
Imports IronXL
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Extensions.Logging

Public Class ExcelProcessor
    Private ReadOnly _logger As ILogger(Of ExcelProcessor)
    Private ReadOnly _workingDirectory As String

    Public Sub New(logger As ILogger(Of ExcelProcessor), workingDirectory As String)
        _logger = logger
        _workingDirectory = workingDirectory
    End Sub

    Public Async Function ProcessExcelFileAsync(fileName As String) As Task
        Try
            Dim filePath = Path.Combine(_workingDirectory, fileName)

            ' Validate file exists
            If Not File.Exists(filePath) Then
                _logger.LogError($"File not found: {filePath}")
                Throw New FileNotFoundException("Excel file not found", fileName)
            End If

            ' Load workbook with error handling
            _logger.LogInformation($"Loading Excel file: {fileName}")
            Dim workBook As WorkBook = WorkBook.Load(filePath)

            ' Process each worksheet
            For Each worksheet In workBook.WorkSheets
                _logger.LogInformation($"Processing worksheet: {worksheet.Name}")
                Await ProcessWorksheetAsync(worksheet)
            Next

            ' Save with timestamp for version control
            Dim outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
            Dim 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 ex As Exception
            _logger.LogError(ex, $"Error processing Excel file: {fileName}")
            Throw
        End Try
    End Function

    Private Async Function ProcessWorksheetAsync(worksheet As WorkSheet) As Task
        ' Example: Update timestamp in specific cell
        Dim timestampCell = worksheet("A1")
        If timestampCell.StringValue = "Last Updated:" Then
            worksheet("B1").Value = DateTime.Now
            worksheet("B1").FormatString = "yyyy-MM-dd HH:mm:ss"
        End If

        ' Example: Process data rows asynchronously
        Await Task.Run(Sub()
                           For row As Integer = 2 To worksheet.RowCount
                               ' Skip empty rows
                               If worksheet($"A{row}").IsEmpty Then
                                   Continue For
                               End If

                               ' Apply business logic
                               Dim quantity = worksheet($"B{row}").IntValue
                               Dim price = worksheet($"C{row}").DoubleValue
                               worksheet($"D{row}").Value = quantity * price
                               worksheet($"E{row}").Formula = $"=D{row}*0.08" ' Tax calculation
                           Next
                       End Sub)
    End Function
End Class
$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");
    }
}
Imports IronXL
Imports System
Imports System.Linq
Imports System.Collections.Generic

Public Class CellEditingExamples
    Public Shared Sub DemonstrateVariousCellEdits()
        Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
        Dim sheet As WorkSheet = 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
        Dim rowIndex As Integer = 5
        Dim columnLetter As String = "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
        Dim 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
        For Each cell In sheet("J1:J10")
            cell.Value = (New Random()).Next(0, 100)
            If cell.IntValue > 50 Then
                cell.Style.BackgroundColor = "#90EE90" ' Light green for high values
            Else
                cell.Style.BackgroundColor = "#FFB6C1" ' Light red for low values
            End If
        Next

        ' 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")
    End Sub
End Class
$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");
    }
}
Imports IronXL
Imports System
Imports System.Diagnostics

Public Class BulkCellOperations
    Public Shared Sub PerformBulkUpdates()
        Dim stopwatch = Stopwatch.StartNew()

        Dim workBook As WorkBook = WorkBook.Load("inventory.xlsx")
        Dim sheet As WorkSheet = 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
        Dim ranges = {"F1:F10", "H1:H10", "J1:J10"}
        For Each range In ranges
            sheet(range).Value = "Batch Update"
            sheet(range).Style.BottomBorder.Type = BorderType.Double
        Next

        ' Method 6: Conditional bulk updates
        Dim dataRange = sheet("K1:K100")
        For Each cell In dataRange
            ' Generate test data
            cell.Value = New Random().Next(1, 1000)

            ' Apply conditional formatting based on value
            If cell.IntValue > 750 Then
                cell.Style.BackgroundColor = "#00FF00" ' Green for high values
                cell.Style.Font.Bold = True
            ElseIf cell.IntValue < 250 Then
                cell.Style.BackgroundColor = "#FF0000" ' Red for low values
                cell.Style.Font.Color = "#FFFFFF"
            End If
        Next

        stopwatch.Stop()
        Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms")

        workBook.SaveAs("inventory_bulk_updated.xlsx")
    End Sub
End Class
$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);
    }
}
Imports IronXL
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks

Public Class InteractiveExcelEditor
    Public Class EditRequest
        Public Property FileName As String
        Public Property WorksheetName As String
        Public Property CellUpdates As Dictionary(Of String, Object)
        Public Property RangeUpdates As List(Of RangeUpdate)
    End Class

    Public Class RangeUpdate
        Public Property Range As String
        Public Property Value As Object
        Public Property Style As CellStyle
    End Class

    Public Class CellStyle
        Public Property BackgroundColor As String
        Public Property Bold As Boolean
        Public Property NumberFormat As String
    End Class

    Public Async Function ProcessEditRequestAsync(request As EditRequest) As Task(Of String)
        Try
            ' Load workbook
            Dim workBook As WorkBook = WorkBook.Load(request.FileName)
            Dim sheet As WorkSheet = If(String.IsNullOrEmpty(request.WorksheetName), workBook.DefaultWorkSheet, workBook.GetWorkSheet(request.WorksheetName))

            ' Process individual cell updates
            If request.CellUpdates IsNot Nothing Then
                For Each update In request.CellUpdates
                    Dim cell = sheet(update.Key)
                    cell.Value = update.Value

                    ' Auto-detect and apply appropriate formatting
                    If TypeOf update.Value Is Decimal OrElse TypeOf update.Value Is Double Then
                        cell.FormatString = "#,##0.00"
                    ElseIf TypeOf update.Value Is DateTime Then
                        cell.FormatString = "yyyy-MM-dd"
                    End If
                Next
            End If

            ' Process range updates
            If request.RangeUpdates IsNot Nothing Then
                For Each rangeUpdate In request.RangeUpdates
                    Dim range = sheet(rangeUpdate.Range)
                    range.Value = rangeUpdate.Value

                    ' Apply styling if provided
                    If rangeUpdate.Style IsNot Nothing Then
                        If Not String.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor) Then
                            range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor
                        End If

                        If rangeUpdate.Style.Bold Then
                            range.Style.Font.Bold = True
                        End If

                        If Not String.IsNullOrEmpty(rangeUpdate.Style.NumberFormat) Then
                            range.FormatString = rangeUpdate.Style.NumberFormat
                        End If
                    End If
                Next
            End If

            ' Generate unique output filename
            Dim outputFile As String = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}"
            workBook.SaveAs(outputFile)

            Return outputFile
        Catch ex As Exception
            Throw New InvalidOperationException($"Failed to process edit request: {ex.Message}", ex)
        End Try
    End Function

    ' Example REST API endpoint implementation
    Public Shared Async Function HandleApiRequest(jsonRequest As String) As Task(Of String)
        Dim request = System.Text.Json.JsonSerializer.Deserialize(Of EditRequest)(jsonRequest)
        Dim editor = New InteractiveExcelEditor()
        Return Await editor.ProcessEditRequestAsync(request)
    End Function
End Class
$vbLabelText   $csharpLabel

將 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
# 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 操作,實現更簡潔的部署

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

常見問題解答

在 .NET Core 應用程式中使用 Excel 的目的為何?

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,您可以同時編輯 Excel 表單中的單元格範圍。使用語法 ws["A1:A9"].Value = "new value"; 來為多個儲存格指定值,其中 ws 是一個 WorkSheet 物件。

在 .NET Core 中編輯 Excel 檔案時,該如何處理使用者輸入?

IronXL 可透過控制台或使用者介面擷取使用者的輸入,以處理使用者的輸入,然後可用於定義 Excel 試算表中的儲存格範圍和更新值。

在 .NET Core 中,Excel 的操作使用何種程式語言?

C# 用於在 .NET Core 應用程式中使用 IronXL library 程式化操作 Excel 檔案。

是否有在 .NET Core 中處理 Excel 檔案的教學?

是的,使用 C# 與 IronXL.Excel 閱讀和操作 Excel 檔案的全面教學。您可以在 IronXL 網站上找到其他資源和範例專案。

在 .NET Core 中使用 Excel 函式庫的相容性要求為何?

IronXL 支援各種版本的 .NET Core。詳細的相容性資訊可在其網站上的 IronXL 文件中找到。

在哪裡可以取得 Excel 函式庫的 API 文件?

IronXL 的 API 文件可線上取得,提供所有命名空間、方法和功能的詳細資訊。請造訪 IronXL 網站存取此資源。

Curtis Chau
技術撰稿人

Curtis Chau 擁有電腦科學學士學位(卡爾頓大學),專長於前端開發,精通 Node.js、TypeScript、JavaScript 和 React。Curtis 對製作直覺且美觀的使用者介面充滿熱情,他喜歡使用現代化的架構,並製作結構良好且視覺上吸引人的手冊。

除了開發之外,Curtis 對物聯網 (IoT) 也有濃厚的興趣,他喜歡探索整合硬體與軟體的創新方式。在空閒時間,他喜歡玩遊戲和建立 Discord bots,將他對技術的熱愛與創意結合。