跳至頁尾內容
使用 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!");
    }
}
$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
            }
        });
    }
}
$vbLabelText   $csharpLabel

錯誤處理的最佳實踐

可靠的錯誤處理對於生產環境部署至關重要。 上述範例示範了日誌整合和正確的異常處理,這對於偵錯容器化環境中的問題至關重要,因為在容器化環境中您可能無法直接存取執行時間。請考慮實施安全措施並檢查您的使用情境下的檔案大小限制

編輯特定單元格值

讓我們來探討修改單元格值的不同技術,從簡單的更新到複雜的資料轉換。 IronXL 提供直覺的方法將值寫入 Excel 儲存格,同時支援各種資料類型和格式。 您也可以根據需要複製儲存格清除儲存格內容

using IronXL;
using System;
using System.Linq;
using System.Collections.Generic;

public class CellEditingExamples
{
    public static void DemonstrateVariousCellEdits()
    {
        WorkBook workBook = WorkBook.Load("data.xlsx");
        WorkSheet sheet = workBook.DefaultWorkSheet;

        // 1. Simple value assignment
        sheet["A1"].Value = "Product Name";
        sheet["B1"].Value = 99.99;
        sheet["C1"].Value = true;
        sheet["D1"].Value = DateTime.Now;

        // 2. Using cell references with variables
        int rowIndex = 5;
        string columnLetter = "E";
        sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference";

        // 3. Setting values with specific formatting
        sheet["F1"].Value = 0.175;
        sheet["F1"].FormatString = "0.00%"; // Display as 17.50%

        // 4. Currency formatting
        sheet["G1"].Value = 1234.56;
        sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56

        // 5. Date formatting variations
        var dateCell = sheet["H1"];
        dateCell.Value = DateTime.Now;
        dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024"

        // 6. Setting hyperlinks
        sheet["I1"].Value = "Visit Documentation";
        sheet["I1"].Hyperlink = "___PROTECTED_URL_54___";

        // 7. Applying conditional formatting
        foreach (var cell in sheet["J1:J10"])
        {
            cell.Value = new Random().Next(0, 100);
            if (cell.IntValue > 50)
            {
                cell.Style.BackgroundColor = "#90EE90"; // Light green for high values
            }
            else
            {
                cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values
            }
        }

        // 8. Working with formulas
        sheet["K1"].Formula = "=SUM(B1:B10)";
        sheet["K2"].Formula = "=AVERAGE(B1:B10)";
        sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")";

        workBook.SaveAs("data_edited.xlsx");
    }
}
using IronXL;
using System;
using System.Linq;
using System.Collections.Generic;

public class CellEditingExamples
{
    public static void DemonstrateVariousCellEdits()
    {
        WorkBook workBook = WorkBook.Load("data.xlsx");
        WorkSheet sheet = workBook.DefaultWorkSheet;

        // 1. Simple value assignment
        sheet["A1"].Value = "Product Name";
        sheet["B1"].Value = 99.99;
        sheet["C1"].Value = true;
        sheet["D1"].Value = DateTime.Now;

        // 2. Using cell references with variables
        int rowIndex = 5;
        string columnLetter = "E";
        sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference";

        // 3. Setting values with specific formatting
        sheet["F1"].Value = 0.175;
        sheet["F1"].FormatString = "0.00%"; // Display as 17.50%

        // 4. Currency formatting
        sheet["G1"].Value = 1234.56;
        sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56

        // 5. Date formatting variations
        var dateCell = sheet["H1"];
        dateCell.Value = DateTime.Now;
        dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024"

        // 6. Setting hyperlinks
        sheet["I1"].Value = "Visit Documentation";
        sheet["I1"].Hyperlink = "___PROTECTED_URL_54___";

        // 7. Applying conditional formatting
        foreach (var cell in sheet["J1:J10"])
        {
            cell.Value = new Random().Next(0, 100);
            if (cell.IntValue > 50)
            {
                cell.Style.BackgroundColor = "#90EE90"; // Light green for high values
            }
            else
            {
                cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values
            }
        }

        // 8. Working with formulas
        sheet["K1"].Formula = "=SUM(B1:B10)";
        sheet["K2"].Formula = "=AVERAGE(B1:B10)";
        sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")";

        workBook.SaveAs("data_edited.xlsx");
    }
}
$vbLabelText   $csharpLabel

高效處理不同資料類型

IronXL 會自動偵測和轉換資料類型,但明確格式化可確保正確顯示。 該庫支援設定貨幣、百分比、日期和自訂模式的儲存格資料格式。 您可以探索Excel 數位格式,以了解更多進階格式設定選項。 此外,您還可以自訂單元格字體和大小,套用背景圖案和顏色,以及配置單元格邊框和對齊方式

為多個單元格賦值

批次操作對於提高 Excel 的處理效率至關重要。 IronXL 提供有效的範圍選擇功能,可輕鬆同時更新多個儲存格。 您還可以根據需要新增行和列插入新行和列以及合併儲存格

using IronXL;
using System;
using System.Diagnostics;

public class BulkCellOperations
{
    public static void PerformBulkUpdates()
    {
        var stopwatch = Stopwatch.StartNew();

        WorkBook workBook = WorkBook.Load("inventory.xlsx");
        WorkSheet sheet = workBook.DefaultWorkSheet;

        // Method 1: Update entire column
        sheet["A:A"].Value = "Updated";
        Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms");

        // Method 2: Update specific range
        sheet["B2:B100"].Value = DateTime.Now.ToShortDateString();

        // Method 3: Update entire row
        sheet["1:1"].Style.Font.Bold = true;
        sheet["1:1"].Style.BackgroundColor = "#333333";
        sheet["1:1"].Style.Font.Color = "#FFFFFF";

        // Method 4: Update rectangular range
        sheet["C2:E50"].Formula = "=ROW()*COLUMN()";

        // Method 5: Update non-contiguous ranges efficiently
        var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" };
        foreach (var range in ranges)
        {
            sheet[range].Value = "Batch Update";
            sheet[range].Style.BottomBorder.Type = BorderType.Double;
        }

        // Method 6: Conditional bulk updates
        var dataRange = sheet["K1:K100"];
        foreach (var cell in dataRange)
        {
            // Generate test data
            cell.Value = new Random().Next(1, 1000);

            // Apply conditional formatting based on value
            if (cell.IntValue > 750)
            {
                cell.Style.BackgroundColor = "#00FF00"; // Green for high values
                cell.Style.Font.Bold = true;
            }
            else if (cell.IntValue < 250)
            {
                cell.Style.BackgroundColor = "#FF0000"; // Red for low values
                cell.Style.Font.Color = "#FFFFFF";
            }
        }

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

        workBook.SaveAs("inventory_bulk_updated.xlsx");
    }
}
using IronXL;
using System;
using System.Diagnostics;

public class BulkCellOperations
{
    public static void PerformBulkUpdates()
    {
        var stopwatch = Stopwatch.StartNew();

        WorkBook workBook = WorkBook.Load("inventory.xlsx");
        WorkSheet sheet = workBook.DefaultWorkSheet;

        // Method 1: Update entire column
        sheet["A:A"].Value = "Updated";
        Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms");

        // Method 2: Update specific range
        sheet["B2:B100"].Value = DateTime.Now.ToShortDateString();

        // Method 3: Update entire row
        sheet["1:1"].Style.Font.Bold = true;
        sheet["1:1"].Style.BackgroundColor = "#333333";
        sheet["1:1"].Style.Font.Color = "#FFFFFF";

        // Method 4: Update rectangular range
        sheet["C2:E50"].Formula = "=ROW()*COLUMN()";

        // Method 5: Update non-contiguous ranges efficiently
        var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" };
        foreach (var range in ranges)
        {
            sheet[range].Value = "Batch Update";
            sheet[range].Style.BottomBorder.Type = BorderType.Double;
        }

        // Method 6: Conditional bulk updates
        var dataRange = sheet["K1:K100"];
        foreach (var cell in dataRange)
        {
            // Generate test data
            cell.Value = new Random().Next(1, 1000);

            // Apply conditional formatting based on value
            if (cell.IntValue > 750)
            {
                cell.Style.BackgroundColor = "#00FF00"; // Green for high values
                cell.Style.Font.Bold = true;
            }
            else if (cell.IntValue < 250)
            {
                cell.Style.BackgroundColor = "#FF0000"; // Red for low values
                cell.Style.Font.Color = "#FFFFFF";
            }
        }

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

        workBook.SaveAs("inventory_bulk_updated.xlsx");
    }
}
$vbLabelText   $csharpLabel

靶場作業效率

範圍操作以單一命令的形式執行,而不是遍歷單一單元格,從而顯著提高效能。 在處理大型資料集或在資源受限的容器環境中運作時,這種效率至關重要。 透過選擇和操作範圍,可以用最少的程式碼實現有效的資料轉換。 您也可以對儲存格區域進行排序修剪儲存格區域以及合併多個區域

常見的範圍選擇模式

圖案句法描述
列範圍"A:A"選擇 A 列的整個位置
行範圍1:1選擇整行 1
矩形範圍A1:C3選擇一個 3x3 的方塊
命名範圍建立和使用命名範圍為了清晰起見
動態範圍以程式設計方式建構範圍字串靈活選擇

使用使用者輸入編輯儲存格

當與使用者輸入或外部資料來源結合使用時,互動式 Excel 編輯功能才能發揮最大效用。 這種方法對於建立接受參數並產生自訂報告的 API 非常有價值。 您可能需要從各種來源匯入 Excel 資料將其匯出為不同的格式

using IronXL;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class InteractiveExcelEditor
{
    public class EditRequest
    {
        public string FileName { get; set; }
        public string WorksheetName { get; set; }
        public Dictionary<string, object> CellUpdates { get; set; }
        public List<RangeUpdate> RangeUpdates { get; set; }
    }

    public class RangeUpdate
    {
        public string Range { get; set; }
        public object Value { get; set; }
        public CellStyle Style { get; set; }
    }

    public class CellStyle
    {
        public string BackgroundColor { get; set; }
        public bool Bold { get; set; }
        public string NumberFormat { get; set; }
    }

    public async Task<string> ProcessEditRequestAsync(EditRequest request)
    {
        try
        {
            // Load workbook
            WorkBook workBook = WorkBook.Load(request.FileName);
            WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName) 
                ? workBook.DefaultWorkSheet 
                : workBook.GetWorkSheet(request.WorksheetName);

            // Process individual cell updates
            if (request.CellUpdates != null)
            {
                foreach (var update in request.CellUpdates)
                {
                    var cell = sheet[update.Key];
                    cell.Value = update.Value;

                    // Auto-detect and apply appropriate formatting
                    if (update.Value is decimal || update.Value is double)
                    {
                        cell.FormatString = "#,##0.00";
                    }
                    else if (update.Value is DateTime)
                    {
                        cell.FormatString = "yyyy-MM-dd";
                    }
                }
            }

            // Process range updates
            if (request.RangeUpdates != null)
            {
                foreach (var rangeUpdate in request.RangeUpdates)
                {
                    var range = sheet[rangeUpdate.Range];
                    range.Value = rangeUpdate.Value;

                    // Apply styling if provided
                    if (rangeUpdate.Style != null)
                    {
                        if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor))
                            range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor;

                        if (rangeUpdate.Style.Bold)
                            range.Style.Font.Bold = true;

                        if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat))
                            range.FormatString = rangeUpdate.Style.NumberFormat;
                    }
                }
            }

            // Generate unique output filename
            string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}";
            workBook.SaveAs(outputFile);

            return outputFile;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex);
        }
    }

    // Example REST API endpoint implementation
    public static async Task<string> HandleApiRequest(string jsonRequest)
    {
        var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest);
        var editor = new InteractiveExcelEditor();
        return await editor.ProcessEditRequestAsync(request);
    }
}
using IronXL;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

public class InteractiveExcelEditor
{
    public class EditRequest
    {
        public string FileName { get; set; }
        public string WorksheetName { get; set; }
        public Dictionary<string, object> CellUpdates { get; set; }
        public List<RangeUpdate> RangeUpdates { get; set; }
    }

    public class RangeUpdate
    {
        public string Range { get; set; }
        public object Value { get; set; }
        public CellStyle Style { get; set; }
    }

    public class CellStyle
    {
        public string BackgroundColor { get; set; }
        public bool Bold { get; set; }
        public string NumberFormat { get; set; }
    }

    public async Task<string> ProcessEditRequestAsync(EditRequest request)
    {
        try
        {
            // Load workbook
            WorkBook workBook = WorkBook.Load(request.FileName);
            WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName) 
                ? workBook.DefaultWorkSheet 
                : workBook.GetWorkSheet(request.WorksheetName);

            // Process individual cell updates
            if (request.CellUpdates != null)
            {
                foreach (var update in request.CellUpdates)
                {
                    var cell = sheet[update.Key];
                    cell.Value = update.Value;

                    // Auto-detect and apply appropriate formatting
                    if (update.Value is decimal || update.Value is double)
                    {
                        cell.FormatString = "#,##0.00";
                    }
                    else if (update.Value is DateTime)
                    {
                        cell.FormatString = "yyyy-MM-dd";
                    }
                }
            }

            // Process range updates
            if (request.RangeUpdates != null)
            {
                foreach (var rangeUpdate in request.RangeUpdates)
                {
                    var range = sheet[rangeUpdate.Range];
                    range.Value = rangeUpdate.Value;

                    // Apply styling if provided
                    if (rangeUpdate.Style != null)
                    {
                        if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor))
                            range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor;

                        if (rangeUpdate.Style.Bold)
                            range.Style.Font.Bold = true;

                        if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat))
                            range.FormatString = rangeUpdate.Style.NumberFormat;
                    }
                }
            }

            // Generate unique output filename
            string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}";
            workBook.SaveAs(outputFile);

            return outputFile;
        }
        catch (Exception ex)
        {
            throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex);
        }
    }

    // Example REST API endpoint implementation
    public static async Task<string> HandleApiRequest(string jsonRequest)
    {
        var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest);
        var editor = new InteractiveExcelEditor();
        return await editor.ProcessEditRequestAsync(request);
    }
}
$vbLabelText   $csharpLabel

將 Excel 編輯功能與 CI/CD 管線集成

對於DevOps場景,將 Excel 處理整合到建置和部署管道中。 您可以在 ASP.NET 應用程式中讀取 Excel 文件,也可以根據需要使用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 的目的為何?

在 .NET Core 應用程式中,Excel 用於高效的資料管理和操作。 IronXL 允許開發人員使用 C# 以程式方式載入、編輯和儲存 Excel 文件,從而提高工作效率和資料處理能力。

如何在 .NET Core 專案中安裝 Excel 程式庫?

您可以使用 NuGet 套件管理器,透過下列指令將dotnet add package IronXL.Excel 。或者,您可以直接從 IronXL 網站下載 DLL 檔案。

在 .NET Core 中載入 Excel 檔案的步驟是什麼?

若要在 .NET Core 中使用 IronXL 載入 Excel 文件,請使用WorkBook.Load方法。例如, WorkBook wb = WorkBook.Load("sample.xlsx");將載入名為「sample.xlsx」的 Excel 工作簿。

我可以使用 .NET Core 編輯 Excel 表格中的一系列儲存格嗎?

是的,使用 IronXL,您可以同時編輯 Excel 工作表中的多個儲存格。使用語法ws["A1:A9"].Value = "new value";可以為多個單元格賦值,其中wsWorkSheet物件。

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

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

在.NET Core中,用於Excel操作的程式語言是什麼?

在 .NET Core 應用程式中,使用 IronXL 程式庫,透過 C# 以程式設計方式操作 Excel 檔案。

有沒有關於如何在 .NET Core 中處理 Excel 檔案的教學課程?

是的,我們提供了使用 IronXL 和 C# 讀取和操作 Excel 檔案的全面教學。更多資源和範例項目可以在 IronXL 網站上找到。

在 .NET Core 中使用 Excel 函式庫有哪些相容性要求?

IronXL 支援多個版本的 .NET Core。詳細的兼容性資訊可以在 IronXL 官網的文檔中找到。

我可以在哪裡找到Excel庫的API文件?

IronXL 的 API 文件已上線,其中詳細介紹了所有命名空間、方法和功能。請造訪 IronXL 網站以取得此資源。

喬迪·巴迪亞
軟體工程師
喬迪精通Python、C#和C++,除了在Iron Software運用這些技能外,他還從事遊戲程式設計。他參與產品測試、產品開發和研究等工作,為產品的持續改進做出了巨大貢獻。豐富的經驗讓他始終保持挑戰性和工作熱情,他表示這是他最喜歡在Iron Software工作的原因之一。喬迪在佛羅裡達州邁阿密長大,畢業於佛羅裡達大學,主修電腦科學和統計學。