跳過到頁腳內容
使用 IRONXL

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

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

為何選擇 IronXL for .NET Core Excel 開發?

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

請考慮以下典型情境:您的團隊需要從各種資料來源生成每月績效報告,根據計算結果修改特定儲存格,並將此功能部署於跨多個環境的 Docker 容器中。 傳統的 Excel 自動化方案需要在每台伺服器上安裝 Office,這會造成授權管理上的困擾及部署上的複雜性。 IronXL 透過提供一套可在任何 .NET Core 應用程式運行環境中運作的完整解決方案,消除了這些障礙。

此函式庫擅長從零開始建立試算表、透過程式碼管理工作表,並能在不依賴外部元件的情況下進行檔案格式轉換。 無論您是建立微服務、無伺服器函數還是容器化應用程序,IronXL 都能自然地整合到現代工作流程中。

為何選擇 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 提供靈活的授權方案,適用於從單一伺服器應用程式到 Enterprise 解決方案等不同部署規模。 對於網頁應用程式,您可以在 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

為何此模式最適合用於自動化?

此模式非常適合用於自動化工作流程,因為它具有確定性且無需使用者互動。 您可以安排此程式碼在容器中運行,透過事件或基於時間的計劃觸發,使其成為自動化場景的理想選擇。 能夠透過程式碼開啟編輯 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 提供超越基本儲存格編輯的廣泛功能:

優化 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 庫?

您可以在 .NET Core 專案中使用 NuGet 包管理器與命令 dotnet add package IronXL.Excel 安裝 IronXL 庫。或者,您可以從 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 應用中以程序化方式處理 Excel 文件,使用 IronXL 庫。

是否有關於在 .NET Core 中操作 Excel 文件的教程?

有,用 C# 與 IronXL 讀取和操作 Excel 文件的綜合教程可用。IronXL 網站提供其他資源和示例專案。

.NET Core 中使用 Excel 庫的兼容性要求是什麼?

IronXL 支援各個版本的 .NET Core。詳細的兼容性信息可以在 IronXL 文檔中找到。

在哪裡可以訪問 Excel 庫的 API 文檔?

IronXL 提供在線的 API 文檔,提供所有命名空間、方法及功能的詳細信息。訪問 IronXL 網站來取得此資源。

Jordi Bardia
軟體工程師
Jordi 在 Python、C# 和 C++ 上最得心應手,當他不在 Iron Software 展現技術時,便在做遊戲編程。在分担產品测测试,產品開發和研究的责任時,Jordi 為持续的產品改進增值。他说这种多样化的经验使他受到挑战并保持参与, 而这也是他与 Iron Software 中工作一大乐趣。Jordi 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我