跳過到頁腳內容
使用 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 工作流程的工程師來說,這項功能尤其有價值。

設想這樣一個典型場景:您的團隊需要從各種資料來源產生每月績效報告,根據計算結果修改特定單元格,並將此功能部署到跨多個環境的 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提供靈活的授權選項,適用於不同的部署規模,從單一伺服器應用程式到企業級解決方案。 對於 Web 應用程序,您可以在 web.config 中設定許可證以進行集中管理。 隨著需求的增長,請考慮擴展應用程式的授權升級選項

改進IronXL在容器環境中的效能

部署到容器時,請考慮以下符合Docker 設定最佳實務的最佳化策略:

# Dockerfile example for IronXL applications
FROM mcr.microsoft.com/dotnet/runtime:6.0-alpine AS base
WORKDIR /app

# Install required dependencies for Excel processing
RUN apk add --no-cache \
    icu-libs \
    krb5-libs \
    libgcc \
    libintl \
    libssl1.1 \
    libstdc++ \
    zlib

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["YourProject.csproj", "./"]
RUN dotnet restore "YourProject.csproj"
COPY . .
RUN dotnet build "YourProject.csproj" -c Release -o /app/build

FROM build AS publish
RUN dotnet publish "YourProject.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "YourProject.dll"]

在.NET Core中快速修改 Excel 儲存格

以下是一個演示核心功能的實際範例。 這段程式碼示範如何載入現有的 Excel 檔案並修改特定儲存格:

using IronXL;
using System;

class QuickStartExample
{
    static void Main()
    {
        // Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
        WorkBook workBook = WorkBook.Load("sales_report.xlsx");

        // Access the default worksheet (usually first sheet)
        WorkSheet sheet = workBook.DefaultWorkSheet;

        // Modify individual cells with different data types
        sheet["A1"].Value = "Q4 Sales Report";  // String value
        sheet["B2"].Value = DateTime.Now;       // Date value
        sheet["C2"].Value = 158750.50;          // Numeric value

        // Apply formulas for calculations
        sheet["D2"].Formula = "=C2*1.15";       // 15% markup
        sheet["E2"].Formula = "=D2-C2";         // Profit calculation

        // Bulk update a range of cells
        sheet["A5:A15"].Value = "Updated by Automation";

        // Style the header row
        sheet["A1:E1"].Style.Font.Bold = true;
        sheet["A1:E1"].Style.BackgroundColor = "#1F4788";
        sheet["A1:E1"].Style.Font.Color = "#FFFFFF";

        // Save the modified workbook
        workBook.SaveAs("sales_report_updated.xlsx");

        Console.WriteLine("Excel file updated successfully!");
    }
}
using IronXL;
using System;

class QuickStartExample
{
    static void Main()
    {
        // Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
        WorkBook workBook = WorkBook.Load("sales_report.xlsx");

        // Access the default worksheet (usually first sheet)
        WorkSheet sheet = workBook.DefaultWorkSheet;

        // Modify individual cells with different data types
        sheet["A1"].Value = "Q4 Sales Report";  // String value
        sheet["B2"].Value = DateTime.Now;       // Date value
        sheet["C2"].Value = 158750.50;          // Numeric value

        // Apply formulas for calculations
        sheet["D2"].Formula = "=C2*1.15";       // 15% markup
        sheet["E2"].Formula = "=D2-C2";         // Profit calculation

        // Bulk update a range of cells
        sheet["A5:A15"].Value = "Updated by Automation";

        // Style the header row
        sheet["A1:E1"].Style.Font.Bold = true;
        sheet["A1:E1"].Style.BackgroundColor = "#1F4788";
        sheet["A1:E1"].Style.Font.Color = "#FFFFFF";

        // Save the modified workbook
        workBook.SaveAs("sales_report_updated.xlsx");

        Console.WriteLine("Excel file updated successfully!");
    }
}
$vbLabelText   $csharpLabel

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

這種模式非常適合自動化工作流程,因為它具有確定性,不需要使用者互動。 您可以安排此程式碼在容器中運行,透過事件或基於時間的計劃觸發,使其成為自動化場景的理想選擇。 能夠以程式設計方式開啟和編輯Excel 工作表,可以實現有效的自動化。

啟動一個.NET Core Excel 編輯項目

建立可靠的 Excel 編輯解決方案需要正確的專案設定。讓我們建立一個完整的範例,示範生產部署的最佳實踐,包括錯誤處理日誌記錄

using IronXL;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public class ExcelProcessor
{
    private readonly ILogger<ExcelProcessor> _logger;
    private readonly string _workingDirectory;

    public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory)
    {
        _logger = logger;
        _workingDirectory = workingDirectory;
    }

    public async Task ProcessExcelFileAsync(string fileName)
    {
        try
        {
            var filePath = Path.Combine(_workingDirectory, fileName);

            // Validate file exists
            if (!File.Exists(filePath))
            {
                _logger.LogError($"File not found: {filePath}");
                throw new FileNotFoundException("Excel file not found", fileName);
            }

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

            // Process each worksheet
            foreach (var worksheet in workBook.WorkSheets)
            {
                _logger.LogInformation($"Processing worksheet: {worksheet.Name}");
                await ProcessWorksheetAsync(worksheet);
            }

            // Save with timestamp for version control
            var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var outputPath = Path.Combine(_workingDirectory, "output", outputName);

            // Ensure output directory exists
            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            workBook.SaveAs(outputPath);
            _logger.LogInformation($"Saved processed file: {outputName}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error processing Excel file: {fileName}");
            throw;
        }
    }

    private async Task ProcessWorksheetAsync(WorkSheet worksheet)
    {
        // Example: Update timestamp in specific cell
        var timestampCell = worksheet["A1"];
        if (timestampCell.StringValue == "Last Updated:")
        {
            worksheet["B1"].Value = DateTime.Now;
            worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss";
        }

        // Example: Process data rows asynchronously
        await Task.Run(() =>
        {
            for (int row = 2; row <= worksheet.RowCount; row++)
            {
                // Skip empty rows
                if (worksheet[$"A{row}"].IsEmpty)
                    continue;

                // Apply business logic
                var quantity = worksheet[$"B{row}"].IntValue;
                var price = worksheet[$"C{row}"].DoubleValue;
                worksheet[$"D{row}"].Value = quantity * price;
                worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation
            }
        });
    }
}
using IronXL;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

public class ExcelProcessor
{
    private readonly ILogger<ExcelProcessor> _logger;
    private readonly string _workingDirectory;

    public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory)
    {
        _logger = logger;
        _workingDirectory = workingDirectory;
    }

    public async Task ProcessExcelFileAsync(string fileName)
    {
        try
        {
            var filePath = Path.Combine(_workingDirectory, fileName);

            // Validate file exists
            if (!File.Exists(filePath))
            {
                _logger.LogError($"File not found: {filePath}");
                throw new FileNotFoundException("Excel file not found", fileName);
            }

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

            // Process each worksheet
            foreach (var worksheet in workBook.WorkSheets)
            {
                _logger.LogInformation($"Processing worksheet: {worksheet.Name}");
                await ProcessWorksheetAsync(worksheet);
            }

            // Save with timestamp for version control
            var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
            var outputPath = Path.Combine(_workingDirectory, "output", outputName);

            // Ensure output directory exists
            Directory.CreateDirectory(Path.GetDirectoryName(outputPath));

            workBook.SaveAs(outputPath);
            _logger.LogInformation($"Saved processed file: {outputName}");
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, $"Error processing Excel file: {fileName}");
            throw;
        }
    }

    private async Task ProcessWorksheetAsync(WorkSheet worksheet)
    {
        // Example: Update timestamp in specific cell
        var timestampCell = worksheet["A1"];
        if (timestampCell.StringValue == "Last Updated:")
        {
            worksheet["B1"].Value = DateTime.Now;
            worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss";
        }

        // Example: Process data rows asynchronously
        await Task.Run(() =>
        {
            for (int row = 2; row <= worksheet.RowCount; row++)
            {
                // Skip empty rows
                if (worksheet[$"A{row}"].IsEmpty)
                    continue;

                // Apply business logic
                var quantity = worksheet[$"B{row}"].IntValue;
                var price = worksheet[$"C{row}"].DoubleValue;
                worksheet[$"D{row}"].Value = quantity * price;
                worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation
            }
        });
    }
}
$vbLabelText   $csharpLabel

錯誤處理的最佳實踐

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

編輯特定單元格值

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

高效處理不同資料類型

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

為多個單元格賦值

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

using IronXL;
using System;
using System.Diagnostics;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

靶場作業效率

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

常見的範圍選擇模式

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

對於 DevOps 場景,將 Excel 處理整合到您的建置和部署管道中。 您可以在ASP.NET應用程式中讀取 Excel 文件,或根據需要處理.NET Excel 文件

# Example GitHub Actions workflow
name: Process Excel Reports

on:
  schedule:
    - cron: '0 2 * * *' # Run daily at 2 AM
  workflow_dispatch:

jobs:
  process-excel:
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/dotnet/sdk:6.0

    steps:
    - uses: actions/checkout@v2

    - name: Restore dependencies
      run: dotnet restore

    - name: Build
      run: dotnet build --configuration Release

    - name: Process Excel files
      run: |
        dotnet run -- \
          --input-dir ./data/input \
          --output-dir ./data/output \
          --operation bulk-update

    - name: Upload processed files
      uses: actions/upload-artifact@v2
      with:
        name: processed-excel-files
        path: ./data/output/*.xlsx
# Example GitHub Actions workflow
name: Process Excel Reports

on:
  schedule:
    - cron: '0 2 * * *' # Run daily at 2 AM
  workflow_dispatch:

jobs:
  process-excel:
    runs-on: ubuntu-latest
    container:
      image: mcr.microsoft.com/dotnet/sdk:6.0

    steps:
    - uses: actions/checkout@v2

    - name: Restore dependencies
      run: dotnet restore

    - name: Build
      run: dotnet build --configuration Release

    - name: Process Excel files
      run: |
        dotnet run -- \
          --input-dir ./data/input \
          --output-dir ./data/output \
          --operation bulk-update

    - name: Upload processed files
      uses: actions/upload-artifact@v2
      with:
        name: processed-excel-files
        path: ./data/output/*.xlsx
YAML

更多 Excel 自動化資源

若要擴展您的 Excel 自動化功能,請探索以下專業資源:

探索進階功能

IronXL除了基本的細胞編輯功能外,還提供更廣泛的功能:

-在Blazor應用程式中使用 Excel進行基於 Web 的 Excel 處理 -無需 Interop 即可進行 Excel 操作,實現更簡潔的部署

改進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 庫?

您可以在 .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 在佛罗里达州迈阿密长大,曾在佛罗里达大学学习计算机科学和统计学。

Iron Support Team

We're online 24 hours, 5 days a week.
Chat
Email
Call Me