フッターコンテンツにスキップ
IRONXLの使用

.NET CLI 経由でインストールする (CI/CD パイプラインに推奨)

IronXLを使用すると、開発者はMicrosoft Officeを必要とせず、簡単なC#コードを使用して.NET Coreアプリケーション内のExcelセルを変更できます。セル操作、範囲操作、Windows、Linux、macOSへのデプロイをサポートします。

.NET Core Excel 開発に IronXL を使用する理由

.NET Core で Excel を操作することは、特にクラウド ネイティブおよびコンテナー化された環境における最新のエンタープライズ アプリケーションにとって重要です。 IronXL ライブラリは、Microsoft Office のインストールを必要とせずにプラットフォーム間でスムーズに動作する広範な Excel 機能を提供します。 この機能は、レポート生成、データ処理パイプライン、CI/CD ワークフローを自動化するDevOpsエンジニアにとって特に役立ちます。

典型的なシナリオを考えてみましょう。チームはさまざまなデータ ソースから毎月のパフォーマンス レポートを生成し、計算に基づいて特定のセルを変更し、この機能を複数の環境にわたる Docker コンテナーに展開する必要があります。 従来の Excel 自動化では、各サーバーに Office をインストールする必要があり、ライセンスの問題や展開の複雑さが生じます。 IronXL は、.NET Core アプリケーションが実行されるあらゆる場所で機能する自己完結型ソリューションを提供することで、これらの障壁を排除します。

このライブラリは、スプレッドシートを最初から作成しワークシートをプログラムで管理し、外部依存なしでファイル形式を変換することに優れています。 マイクロサービス、サーバーレス関数、コンテナ化されたアプリケーションのいずれを構築する場合でも、IronXL は最新のDevOpsワークフローに自然に統合されます。

クラウドネイティブ Excel 処理に IronXL を選択する理由

クラウド環境では、軽量で柔軟なソリューションが求められます。 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全体を選択
行範囲"1:1"1行目全体を選択
長方形の範囲A1:C33x3ブロックを選択する
名前付き範囲名前付き範囲を作成して使用する明確にするために
ダイナミックレンジプログラムで範囲文字列を構築する柔軟な選択のために

ユーザー入力によるセルの編集

対話型の 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 は、基本的なセル編集を超えた広範な機能を提供します。

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ワークフローにこれらのパターンを実装して、レポート生成とデータ処理タスクを簡素化しましょう。

よくある質問

Excel を .NET Core アプリケーションで使用する目的は何ですか?

Excel は、効率的なデータ管理と操作のために .NET Core アプリケーションで使用されます。IronXL は、開発者が C# を使用してプログラム的に Excel ファイルをロード、編集、保存することを可能にし、生産性とデータ処理能力を向上させます。

どのようにして .NET Core プロジェクトに Excel ライブラリをインストールできますか?

NuGet パッケージマネージャを使用して dotnet add package IronXL.Excel コマンドで .NET Core プロジェクトに IronXL ライブラリをインストールできます。あるいは、IronXL のウェブサイトから DLL ファイルを直接ダウンロードすることもできます。

.NET Core で Excel ファイルをロードする手順は何ですか?

IronXL を使用して .NET Core で Excel ファイルをロードするには WorkBook.Load メソッドを使用します。例えば、WorkBook wb = WorkBook.Load("sample.xlsx"); は 'sample.xlsx' という名前の Excel ワークブックをロードします。

.NET Core を使用して Excel シートのセル範囲を編集できますか?

はい、IronXL を使用すると、Excel シートのセル範囲を同時に編集することができます。ws["A1:A9"].Value = "new value"; の構文を使って複数のセルに値を割り当てることができます。ここで wsWorkSheet オブジェクトです。

Excel ファイル編集時に .NET Core でユーザー入力をどのように処理しますか?

IronXL は、コンソールやユーザーインターフェースを通じてユーザー入力をキャプチャし、それを使って Excel スプレッドシートの更新対象にするセル範囲と値を定義することができます。

.NET Core で Excel の操作に使用するプログラミング言語は何ですか?

C# は、IronXL ライブラリを使用して .NET Core アプリケーションでプログラム的に Excel ファイルを操作するために使用されます。

.NET Core で Excel ファイルを扱うためのチュートリアルはありますか?

はい、C# で IronXL を使用して Excel ファイルの読み取りと操作に関する包括的なチュートリアルがあります。その他のリソースやサンプルプロジェクトは IronXL のウェブサイトで見つけることができます。

.NET Core で Excel ライブラリを使用するための互換性要件は何ですか?

IronXL はさまざまな .NET Core バージョンをサポートしています。詳細な互換性情報は IronXL ドキュメンテーションのウェブサイトで確認できます。

Excel ライブラリの API ドキュメントはどこでアクセスできますか?

IronXL の API ドキュメンテーションはオンラインで利用可能で、すべての名前空間、メソッド、および機能の詳細が提供されています。このリソースにアクセスするには IronXL のウェブサイトをご覧ください。

カーティス・チャウ
テクニカルライター

Curtis Chauは、カールトン大学でコンピュータサイエンスの学士号を取得し、Node.js、TypeScript、JavaScript、およびReactに精通したフロントエンド開発を専門としています。直感的で美しいユーザーインターフェースを作成することに情熱を持ち、Curtisは現代のフレームワークを用いた開発や、構造の良い視覚的に魅力的なマニュアルの作成を楽しんでいます。

開発以外にも、CurtisはIoT(Internet of Things)への強い関心を持ち、ハードウェアとソフトウェアの統合方法を模索しています。余暇には、ゲームをしたりDiscordボットを作成したりして、技術に対する愛情と創造性を組み合わせています。