.NET CLI 経由でインストールする (CI/CD パイプラインに推奨)
IronXLを使用すると、開発者はMicrosoft Officeを必要とせずに、シンプルなC#コードを使用して.NET Coreアプリケーション内でExcelセルを変更できます。セル操作、範囲操作、およびWindows、Linux、macOSへのデプロイをサポートしています。
.NET Core Excel開発にIronXLを使用する理由とは?
.NET Coreで Excel を操作することは、特にクラウドネイティブ環境やコンテナ環境における最新のEnterpriseアプリケーションにとって非常に重要です。 IronXLライブラリは、Microsoft Officeのインストールを必要とせず、プラットフォームを問わずスムーズに動作する、豊富なExcel機能を提供します。 この機能は、レポート生成、データ処理パイプライン、CI/CDワークフローを自動化するエンジニアにとって特に価値があります。
典型的なシナリオを考えてみましょう。あなたのチームは、さまざまなデータソースから月次パフォーマンスレポートを作成し、計算に基づいて特定のセルを変更し、この機能を複数の環境にわたるDockerコンテナにデプロイする必要があります。 従来のExcel自動化では、各サーバーにOfficeをインストールする必要があり、ライセンスの問題や導入の複雑さを招いていた。 IronXLは、 .NET Coreアプリケーションが実行されるあらゆる環境で動作する自己完結型のソリューションを提供することで、これらの障壁を取り除きます。
このライブラリは、スプレッドシートをゼロから作成したり、ワークシートをプログラムで管理したり、外部ライブラリに依存せずにファイル形式を変換したりすることに優れています。 マイクロサービス、サーバーレス関数、コンテナ化されたアプリケーションを構築する場合でも、 IronXL は最新のワークフローに自然に統合されます。
クラウドネイティブなExcel処理にIronXLを選ぶ理由とは?
クラウド環境では、軽量で柔軟なソリューションが求められる。 IronXLは、 Dockerデプロイメント、 Azure Functions 、 AWS 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" />
本番環境向けライセンスの設定
インストール後、本番環境への展開用にライセンスキーを設定してください。 IronXLは、単一サーバーアプリケーションから企業全体のソリューションまで、さまざまな導入規模に適した柔軟なライセンスオプションを提供します。 Webアプリケーションの場合、ライセンスはweb.configファイルで設定することで一元管理できます。 アプリケーションの拡張性を考慮したライセンス延長や、ニーズの拡大に応じたアップグレードオプションを検討してください。
コンテナ環境向けIronXLの改善
コンテナにデプロイする際は、 Dockerのセットアップにおけるベストプラクティスに沿った以下の最適化戦略を検討してください。
# Dockerfile example for IronXL applications
FROM mcr.microsoft.com/dotnet/runtime:6.0-alpine AS base
WORKDIR /app
# Install required dependencies for Excel processing
RUN apk add --no-cache \
icu-libs \
krb5-libs \
libgcc \
libintl \
libssl1.1 \
libstdc++ \
zlib
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
WORKDIR /src
COPY ["YourProject.csproj", "./"]
RUN dotnet restore "YourProject.csproj"
COPY . .
RUN dotnet build "YourProject.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "YourProject.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "YourProject.dll"]
.NET CoreでExcelセルを素早く変更する方法
以下に、コア機能を示す実例を示します。 このコードは、既存のExcelファイルを読み込み、特定のセルを変更する方法を示しています。
using IronXL;
using System;
class QuickStartExample
{
static void Main()
{
// Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
WorkBook workBook = WorkBook.Load("sales_report.xlsx");
// Access the default worksheet (usually first sheet)
WorkSheet sheet = workBook.DefaultWorkSheet;
// Modify individual cells with different data types
sheet["A1"].Value = "Q4 Sales Report"; // String value
sheet["B2"].Value = DateTime.Now; // Date value
sheet["C2"].Value = 158750.50; // Numeric value
// Apply formulas for calculations
sheet["D2"].Formula = "=C2*1.15"; // 15% markup
sheet["E2"].Formula = "=D2-C2"; // Profit calculation
// Bulk update a range of cells
sheet["A5:A15"].Value = "Updated by Automation";
// Style the header row
sheet["A1:E1"].Style.Font.Bold = true;
sheet["A1:E1"].Style.BackgroundColor = "#1F4788";
sheet["A1:E1"].Style.Font.Color = "#FFFFFF";
// Save the modified workbook
workBook.SaveAs("sales_report_updated.xlsx");
Console.WriteLine("Excel file updated successfully!");
}
}
using IronXL;
using System;
class QuickStartExample
{
static void Main()
{
// Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
WorkBook workBook = WorkBook.Load("sales_report.xlsx");
// Access the default worksheet (usually first sheet)
WorkSheet sheet = workBook.DefaultWorkSheet;
// Modify individual cells with different data types
sheet["A1"].Value = "Q4 Sales Report"; // String value
sheet["B2"].Value = DateTime.Now; // Date value
sheet["C2"].Value = 158750.50; // Numeric value
// Apply formulas for calculations
sheet["D2"].Formula = "=C2*1.15"; // 15% markup
sheet["E2"].Formula = "=D2-C2"; // Profit calculation
// Bulk update a range of cells
sheet["A5:A15"].Value = "Updated by Automation";
// Style the header row
sheet["A1:E1"].Style.Font.Bold = true;
sheet["A1:E1"].Style.BackgroundColor = "#1F4788";
sheet["A1:E1"].Style.Font.Color = "#FFFFFF";
// Save the modified workbook
workBook.SaveAs("sales_report_updated.xlsx");
Console.WriteLine("Excel file updated successfully!");
}
}
Imports IronXL
Imports System
Class QuickStartExample
Shared Sub Main()
' Load existing Excel file - supports XLSX, XLS, XLSM, XLTX
Dim workBook As WorkBook = WorkBook.Load("sales_report.xlsx")
' Access the default worksheet (usually first sheet)
Dim sheet As WorkSheet = workBook.DefaultWorkSheet
' Modify individual cells with different data types
sheet("A1").Value = "Q4 Sales Report" ' String value
sheet("B2").Value = DateTime.Now ' Date value
sheet("C2").Value = 158750.5 ' Numeric value
' Apply formulas for calculations
sheet("D2").Formula = "=C2*1.15" ' 15% markup
sheet("E2").Formula = "=D2-C2" ' Profit calculation
' Bulk update a range of cells
sheet("A5:A15").Value = "Updated by Automation"
' Style the header row
sheet("A1:E1").Style.Font.Bold = True
sheet("A1:E1").Style.BackgroundColor = "#1F4788"
sheet("A1:E1").Style.Font.Color = "#FFFFFF"
' Save the modified workbook
workBook.SaveAs("sales_report_updated.xlsx")
Console.WriteLine("Excel file updated successfully!")
End Sub
End Class
なぜこのパターンは自動化に最適なのか?
このパターンは決定論的でユーザー操作を必要としないため、自動化されたワークフローにおいて完璧に機能します。 このコードは、イベントや時間ベースのスケジュールによってトリガーされるコンテナ内で実行されるようにスケジュールできるため、DevOps 自動化シナリオに最適です。 Excelワークシートを開いてプログラムで編集できる機能は、効果的な自動化の可能性を広げます。
.NET Core Excel編集プロジェクトの開始
信頼性の高いExcel編集ソリューションを構築するには、適切なプロジェクト設定が必要です。エラー処理とログ記録を組み込んだ、本番環境への展開におけるベストプラクティスを示す完全な例を作成してみましょう。
using IronXL;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class ExcelProcessor
{
private readonly ILogger<ExcelProcessor> _logger;
private readonly string _workingDirectory;
public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory)
{
_logger = logger;
_workingDirectory = workingDirectory;
}
public async Task ProcessExcelFileAsync(string fileName)
{
try
{
var filePath = Path.Combine(_workingDirectory, fileName);
// Validate file exists
if (!File.Exists(filePath))
{
_logger.LogError($"File not found: {filePath}");
throw new FileNotFoundException("Excel file not found", fileName);
}
// Load workbook with error handling
_logger.LogInformation($"Loading Excel file: {fileName}");
WorkBook workBook = WorkBook.Load(filePath);
// Process each worksheet
foreach (var worksheet in workBook.WorkSheets)
{
_logger.LogInformation($"Processing worksheet: {worksheet.Name}");
await ProcessWorksheetAsync(worksheet);
}
// Save with timestamp for version control
var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
var outputPath = Path.Combine(_workingDirectory, "output", outputName);
// Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
workBook.SaveAs(outputPath);
_logger.LogInformation($"Saved processed file: {outputName}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error processing Excel file: {fileName}");
throw;
}
}
private async Task ProcessWorksheetAsync(WorkSheet worksheet)
{
// Example: Update timestamp in specific cell
var timestampCell = worksheet["A1"];
if (timestampCell.StringValue == "Last Updated:")
{
worksheet["B1"].Value = DateTime.Now;
worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss";
}
// Example: Process data rows asynchronously
await Task.Run(() =>
{
for (int row = 2; row <= worksheet.RowCount; row++)
{
// Skip empty rows
if (worksheet[$"A{row}"].IsEmpty)
continue;
// Apply business logic
var quantity = worksheet[$"B{row}"].IntValue;
var price = worksheet[$"C{row}"].DoubleValue;
worksheet[$"D{row}"].Value = quantity * price;
worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation
}
});
}
}
using IronXL;
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
public class ExcelProcessor
{
private readonly ILogger<ExcelProcessor> _logger;
private readonly string _workingDirectory;
public ExcelProcessor(ILogger<ExcelProcessor> logger, string workingDirectory)
{
_logger = logger;
_workingDirectory = workingDirectory;
}
public async Task ProcessExcelFileAsync(string fileName)
{
try
{
var filePath = Path.Combine(_workingDirectory, fileName);
// Validate file exists
if (!File.Exists(filePath))
{
_logger.LogError($"File not found: {filePath}");
throw new FileNotFoundException("Excel file not found", fileName);
}
// Load workbook with error handling
_logger.LogInformation($"Loading Excel file: {fileName}");
WorkBook workBook = WorkBook.Load(filePath);
// Process each worksheet
foreach (var worksheet in workBook.WorkSheets)
{
_logger.LogInformation($"Processing worksheet: {worksheet.Name}");
await ProcessWorksheetAsync(worksheet);
}
// Save with timestamp for version control
var outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx";
var outputPath = Path.Combine(_workingDirectory, "output", outputName);
// Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(outputPath));
workBook.SaveAs(outputPath);
_logger.LogInformation($"Saved processed file: {outputName}");
}
catch (Exception ex)
{
_logger.LogError(ex, $"Error processing Excel file: {fileName}");
throw;
}
}
private async Task ProcessWorksheetAsync(WorkSheet worksheet)
{
// Example: Update timestamp in specific cell
var timestampCell = worksheet["A1"];
if (timestampCell.StringValue == "Last Updated:")
{
worksheet["B1"].Value = DateTime.Now;
worksheet["B1"].FormatString = "yyyy-MM-dd HH:mm:ss";
}
// Example: Process data rows asynchronously
await Task.Run(() =>
{
for (int row = 2; row <= worksheet.RowCount; row++)
{
// Skip empty rows
if (worksheet[$"A{row}"].IsEmpty)
continue;
// Apply business logic
var quantity = worksheet[$"B{row}"].IntValue;
var price = worksheet[$"C{row}"].DoubleValue;
worksheet[$"D{row}"].Value = quantity * price;
worksheet[$"E{row}"].Formula = $"=D{row}*0.08"; // Tax calculation
}
});
}
}
Imports IronXL
Imports System
Imports System.IO
Imports System.Threading.Tasks
Imports Microsoft.Extensions.Logging
Public Class ExcelProcessor
Private ReadOnly _logger As ILogger(Of ExcelProcessor)
Private ReadOnly _workingDirectory As String
Public Sub New(logger As ILogger(Of ExcelProcessor), workingDirectory As String)
_logger = logger
_workingDirectory = workingDirectory
End Sub
Public Async Function ProcessExcelFileAsync(fileName As String) As Task
Try
Dim filePath = Path.Combine(_workingDirectory, fileName)
' Validate file exists
If Not File.Exists(filePath) Then
_logger.LogError($"File not found: {filePath}")
Throw New FileNotFoundException("Excel file not found", fileName)
End If
' Load workbook with error handling
_logger.LogInformation($"Loading Excel file: {fileName}")
Dim workBook As WorkBook = WorkBook.Load(filePath)
' Process each worksheet
For Each worksheet In workBook.WorkSheets
_logger.LogInformation($"Processing worksheet: {worksheet.Name}")
Await ProcessWorksheetAsync(worksheet)
Next
' Save with timestamp for version control
Dim outputName = $"{Path.GetFileNameWithoutExtension(fileName)}_processed_{DateTime.Now:yyyyMMddHHmmss}.xlsx"
Dim outputPath = Path.Combine(_workingDirectory, "output", outputName)
' Ensure output directory exists
Directory.CreateDirectory(Path.GetDirectoryName(outputPath))
workBook.SaveAs(outputPath)
_logger.LogInformation($"Saved processed file: {outputName}")
Catch ex As Exception
_logger.LogError(ex, $"Error processing Excel file: {fileName}")
Throw
End Try
End Function
Private Async Function ProcessWorksheetAsync(worksheet As WorkSheet) As Task
' Example: Update timestamp in specific cell
Dim timestampCell = worksheet("A1")
If timestampCell.StringValue = "Last Updated:" Then
worksheet("B1").Value = DateTime.Now
worksheet("B1").FormatString = "yyyy-MM-dd HH:mm:ss"
End If
' Example: Process data rows asynchronously
Await Task.Run(Sub()
For row As Integer = 2 To worksheet.RowCount
' Skip empty rows
If worksheet($"A{row}").IsEmpty Then
Continue For
End If
' Apply business logic
Dim quantity = worksheet($"B{row}").IntValue
Dim price = worksheet($"C{row}").DoubleValue
worksheet($"D{row}").Value = quantity * price
worksheet($"E{row}").Formula = $"=D{row}*0.08" ' Tax calculation
Next
End Sub)
End Function
End Class
エラー処理のベストプラクティス
信頼性の高いエラー処理は、本番環境への導入において極めて重要です。 上記の例は、ログ記録の統合と適切な例外処理を示しています。これらは、ランタイムに直接アクセスできないコンテナ環境で問題をデバッグする際に不可欠です。ご使用の環境に合わせて、セキュリティ対策の実施とファイルサイズ制限の見直しをご検討ください。
特定のセル値を編集する
セル値を変更するためのさまざまな手法を、単純な更新から複雑なデータ変換まで探ってみましょう。 IronXLは、さまざまなデータ型とフォーマットをサポートしながら、 Excelセルに値を書き込むための直感的な方法を提供します。 必要に応じて、セルをコピーしたり、セルの内容を消去したりすることもできます。
using IronXL;
using System;
using System.Linq;
using System.Collections.Generic;
public class CellEditingExamples
{
public static void DemonstrateVariousCellEdits()
{
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// 1. Simple value assignment
sheet["A1"].Value = "Product Name";
sheet["B1"].Value = 99.99;
sheet["C1"].Value = true;
sheet["D1"].Value = DateTime.Now;
// 2. Using cell references with variables
int rowIndex = 5;
string columnLetter = "E";
sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference";
// 3. Setting values with specific formatting
sheet["F1"].Value = 0.175;
sheet["F1"].FormatString = "0.00%"; // Display as 17.50%
// 4. Currency formatting
sheet["G1"].Value = 1234.56;
sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56
// 5. Date formatting variations
var dateCell = sheet["H1"];
dateCell.Value = DateTime.Now;
dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024"
// 6. Setting hyperlinks
sheet["I1"].Value = "Visit Documentation";
sheet["I1"].Hyperlink = "___PROTECTED_URL_54___";
// 7. Applying conditional formatting
foreach (var cell in sheet["J1:J10"])
{
cell.Value = new Random().Next(0, 100);
if (cell.IntValue > 50)
{
cell.Style.BackgroundColor = "#90EE90"; // Light green for high values
}
else
{
cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values
}
}
// 8. Working with formulas
sheet["K1"].Formula = "=SUM(B1:B10)";
sheet["K2"].Formula = "=AVERAGE(B1:B10)";
sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")";
workBook.SaveAs("data_edited.xlsx");
}
}
using IronXL;
using System;
using System.Linq;
using System.Collections.Generic;
public class CellEditingExamples
{
public static void DemonstrateVariousCellEdits()
{
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// 1. Simple value assignment
sheet["A1"].Value = "Product Name";
sheet["B1"].Value = 99.99;
sheet["C1"].Value = true;
sheet["D1"].Value = DateTime.Now;
// 2. Using cell references with variables
int rowIndex = 5;
string columnLetter = "E";
sheet[$"{columnLetter}{rowIndex}"].Value = "Dynamic Reference";
// 3. Setting values with specific formatting
sheet["F1"].Value = 0.175;
sheet["F1"].FormatString = "0.00%"; // Display as 17.50%
// 4. Currency formatting
sheet["G1"].Value = 1234.56;
sheet["G1"].FormatString = "$#,##0.00"; // Display as $1,234.56
// 5. Date formatting variations
var dateCell = sheet["H1"];
dateCell.Value = DateTime.Now;
dateCell.FormatString = "MMM dd, yyyy"; // Display as "Dec 25, 2024"
// 6. Setting hyperlinks
sheet["I1"].Value = "Visit Documentation";
sheet["I1"].Hyperlink = "___PROTECTED_URL_54___";
// 7. Applying conditional formatting
foreach (var cell in sheet["J1:J10"])
{
cell.Value = new Random().Next(0, 100);
if (cell.IntValue > 50)
{
cell.Style.BackgroundColor = "#90EE90"; // Light green for high values
}
else
{
cell.Style.BackgroundColor = "#FFB6C1"; // Light red for low values
}
}
// 8. Working with formulas
sheet["K1"].Formula = "=SUM(B1:B10)";
sheet["K2"].Formula = "=AVERAGE(B1:B10)";
sheet["K3"].Formula = "=IF(K2>50,\"Above Average\",\"Below Average\")";
workBook.SaveAs("data_edited.xlsx");
}
}
Imports IronXL
Imports System
Imports System.Linq
Imports System.Collections.Generic
Public Class CellEditingExamples
Public Shared Sub DemonstrateVariousCellEdits()
Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim sheet As WorkSheet = workBook.DefaultWorkSheet
' 1. Simple value assignment
sheet("A1").Value = "Product Name"
sheet("B1").Value = 99.99
sheet("C1").Value = True
sheet("D1").Value = DateTime.Now
' 2. Using cell references with variables
Dim rowIndex As Integer = 5
Dim columnLetter As String = "E"
sheet($"{columnLetter}{rowIndex}").Value = "Dynamic Reference"
' 3. Setting values with specific formatting
sheet("F1").Value = 0.175
sheet("F1").FormatString = "0.00%" ' Display as 17.50%
' 4. Currency formatting
sheet("G1").Value = 1234.56
sheet("G1").FormatString = "$#,##0.00" ' Display as $1,234.56
' 5. Date formatting variations
Dim dateCell = sheet("H1")
dateCell.Value = DateTime.Now
dateCell.FormatString = "MMM dd, yyyy" ' Display as "Dec 25, 2024"
' 6. Setting hyperlinks
sheet("I1").Value = "Visit Documentation"
sheet("I1").Hyperlink = "___PROTECTED_URL_54___"
' 7. Applying conditional formatting
For Each cell In sheet("J1:J10")
cell.Value = (New Random()).Next(0, 100)
If cell.IntValue > 50 Then
cell.Style.BackgroundColor = "#90EE90" ' Light green for high values
Else
cell.Style.BackgroundColor = "#FFB6C1" ' Light red for low values
End If
Next
' 8. Working with formulas
sheet("K1").Formula = "=SUM(B1:B10)"
sheet("K2").Formula = "=AVERAGE(B1:B10)"
sheet("K3").Formula = "=IF(K2>50,""Above Average"",""Below Average"")"
workBook.SaveAs("data_edited.xlsx")
End Sub
End Class
さまざまなデータ型を効率的に処理する
IronXLはデータ型を自動的に検出して変換しますが、明示的な書式設定を行うことで適切な表示が保証されます。 このライブラリは、通貨、パーセンテージ、日付、およびカスタムパターンのセルデータ形式を設定することをサポートしています。 高度な書式設定オプションについては、 Excelの数値形式を参照してください。 さらに、セルのフォントやサイズをカスタマイズしたり、背景のパターンや色を適用したり、セルの境界線や配置を設定したりすることもできます。
複数のセルに値を割り当てる
効率的なExcel処理には、一括処理が不可欠です。 IronXLは、複数のセルを同時に簡単に更新できる効果的な範囲選択機能を提供します。 必要に応じて、行や列を追加したり、新しい行や列を挿入したり、セルを結合したりすることもできます。
using IronXL;
using System;
using System.Diagnostics;
public class BulkCellOperations
{
public static void PerformBulkUpdates()
{
var stopwatch = Stopwatch.StartNew();
WorkBook workBook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// Method 1: Update entire column
sheet["A:A"].Value = "Updated";
Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms");
// Method 2: Update specific range
sheet["B2:B100"].Value = DateTime.Now.ToShortDateString();
// Method 3: Update entire row
sheet["1:1"].Style.Font.Bold = true;
sheet["1:1"].Style.BackgroundColor = "#333333";
sheet["1:1"].Style.Font.Color = "#FFFFFF";
// Method 4: Update rectangular range
sheet["C2:E50"].Formula = "=ROW()*COLUMN()";
// Method 5: Update non-contiguous ranges efficiently
var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" };
foreach (var range in ranges)
{
sheet[range].Value = "Batch Update";
sheet[range].Style.BottomBorder.Type = BorderType.Double;
}
// Method 6: Conditional bulk updates
var dataRange = sheet["K1:K100"];
foreach (var cell in dataRange)
{
// Generate test data
cell.Value = new Random().Next(1, 1000);
// Apply conditional formatting based on value
if (cell.IntValue > 750)
{
cell.Style.BackgroundColor = "#00FF00"; // Green for high values
cell.Style.Font.Bold = true;
}
else if (cell.IntValue < 250)
{
cell.Style.BackgroundColor = "#FF0000"; // Red for low values
cell.Style.Font.Color = "#FFFFFF";
}
}
stopwatch.Stop();
Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms");
workBook.SaveAs("inventory_bulk_updated.xlsx");
}
}
using IronXL;
using System;
using System.Diagnostics;
public class BulkCellOperations
{
public static void PerformBulkUpdates()
{
var stopwatch = Stopwatch.StartNew();
WorkBook workBook = WorkBook.Load("inventory.xlsx");
WorkSheet sheet = workBook.DefaultWorkSheet;
// Method 1: Update entire column
sheet["A:A"].Value = "Updated";
Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms");
// Method 2: Update specific range
sheet["B2:B100"].Value = DateTime.Now.ToShortDateString();
// Method 3: Update entire row
sheet["1:1"].Style.Font.Bold = true;
sheet["1:1"].Style.BackgroundColor = "#333333";
sheet["1:1"].Style.Font.Color = "#FFFFFF";
// Method 4: Update rectangular range
sheet["C2:E50"].Formula = "=ROW()*COLUMN()";
// Method 5: Update non-contiguous ranges efficiently
var ranges = new[] { "F1:F10", "H1:H10", "J1:J10" };
foreach (var range in ranges)
{
sheet[range].Value = "Batch Update";
sheet[range].Style.BottomBorder.Type = BorderType.Double;
}
// Method 6: Conditional bulk updates
var dataRange = sheet["K1:K100"];
foreach (var cell in dataRange)
{
// Generate test data
cell.Value = new Random().Next(1, 1000);
// Apply conditional formatting based on value
if (cell.IntValue > 750)
{
cell.Style.BackgroundColor = "#00FF00"; // Green for high values
cell.Style.Font.Bold = true;
}
else if (cell.IntValue < 250)
{
cell.Style.BackgroundColor = "#FF0000"; // Red for low values
cell.Style.Font.Color = "#FFFFFF";
}
}
stopwatch.Stop();
Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms");
workBook.SaveAs("inventory_bulk_updated.xlsx");
}
}
Imports IronXL
Imports System
Imports System.Diagnostics
Public Class BulkCellOperations
Public Shared Sub PerformBulkUpdates()
Dim stopwatch = Stopwatch.StartNew()
Dim workBook As WorkBook = WorkBook.Load("inventory.xlsx")
Dim sheet As WorkSheet = workBook.DefaultWorkSheet
' Method 1: Update entire column
sheet("A:A").Value = "Updated"
Console.WriteLine($"Column update: {stopwatch.ElapsedMilliseconds}ms")
' Method 2: Update specific range
sheet("B2:B100").Value = DateTime.Now.ToShortDateString()
' Method 3: Update entire row
sheet("1:1").Style.Font.Bold = True
sheet("1:1").Style.BackgroundColor = "#333333"
sheet("1:1").Style.Font.Color = "#FFFFFF"
' Method 4: Update rectangular range
sheet("C2:E50").Formula = "=ROW()*COLUMN()"
' Method 5: Update non-contiguous ranges efficiently
Dim ranges = {"F1:F10", "H1:H10", "J1:J10"}
For Each range In ranges
sheet(range).Value = "Batch Update"
sheet(range).Style.BottomBorder.Type = BorderType.Double
Next
' Method 6: Conditional bulk updates
Dim dataRange = sheet("K1:K100")
For Each cell In dataRange
' Generate test data
cell.Value = New Random().Next(1, 1000)
' Apply conditional formatting based on value
If cell.IntValue > 750 Then
cell.Style.BackgroundColor = "#00FF00" ' Green for high values
cell.Style.Font.Bold = True
ElseIf cell.IntValue < 250 Then
cell.Style.BackgroundColor = "#FF0000" ' Red for low values
cell.Style.Font.Color = "#FFFFFF"
End If
Next
stopwatch.Stop()
Console.WriteLine($"Total execution time: {stopwatch.ElapsedMilliseconds}ms")
workBook.SaveAs("inventory_bulk_updated.xlsx")
End Sub
End Class
射撃場運営の効率性
範囲操作は個々のセルを反復処理するのではなく、単一のコマンドとして実行されるため、パフォーマンスが大幅に向上します。 この効率性は、大規模なデータセットを処理する場合や、リソースが限られたコンテナ環境で運用する場合に非常に重要になります。 範囲を選択および操作できる機能により、最小限のコードで効果的なデータ変換が可能になります。 セル範囲の並べ替え、セル範囲のトリミング、複数の範囲の結合も可能です。
一般的な範囲選択パターン
| パターン | 構文 | 翻訳内容 |
|---|---|---|
| 列範囲 | "A:A" | 列A全体を選択します |
| 行範囲 | "1対1" | 行1全体を選択します |
| 長方形の範囲 | "A1:C3" | 3x3ブロックを選択します |
| 名前付き範囲 | 名前付き範囲を作成して使用する | 明確にするために |
| ダイナミックレンジ | 範囲文字列をプログラムで構築する | 柔軟な選択が可能 |
ユーザー入力によるセルの編集
対話型のExcel編集は、ユーザー入力や外部データソースと組み合わせることで効果を発揮します。 このアプローチは、パラメータを受け取り、カスタマイズされたレポートを生成するAPIを構築する際に有効です。 さまざまなソースからExcelデータをインポートしたり、異なる形式でエクスポートしたりしたい場合があるかもしれません。
using IronXL;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class InteractiveExcelEditor
{
public class EditRequest
{
public string FileName { get; set; }
public string WorksheetName { get; set; }
public Dictionary<string, object> CellUpdates { get; set; }
public List<RangeUpdate> RangeUpdates { get; set; }
}
public class RangeUpdate
{
public string Range { get; set; }
public object Value { get; set; }
public CellStyle Style { get; set; }
}
public class CellStyle
{
public string BackgroundColor { get; set; }
public bool Bold { get; set; }
public string NumberFormat { get; set; }
}
public async Task<string> ProcessEditRequestAsync(EditRequest request)
{
try
{
// Load workbook
WorkBook workBook = WorkBook.Load(request.FileName);
WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName)
? workBook.DefaultWorkSheet
: workBook.GetWorkSheet(request.WorksheetName);
// Process individual cell updates
if (request.CellUpdates != null)
{
foreach (var update in request.CellUpdates)
{
var cell = sheet[update.Key];
cell.Value = update.Value;
// Auto-detect and apply appropriate formatting
if (update.Value is decimal || update.Value is double)
{
cell.FormatString = "#,##0.00";
}
else if (update.Value is DateTime)
{
cell.FormatString = "yyyy-MM-dd";
}
}
}
// Process range updates
if (request.RangeUpdates != null)
{
foreach (var rangeUpdate in request.RangeUpdates)
{
var range = sheet[rangeUpdate.Range];
range.Value = rangeUpdate.Value;
// Apply styling if provided
if (rangeUpdate.Style != null)
{
if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor))
range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor;
if (rangeUpdate.Style.Bold)
range.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat))
range.FormatString = rangeUpdate.Style.NumberFormat;
}
}
}
// Generate unique output filename
string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}";
workBook.SaveAs(outputFile);
return outputFile;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex);
}
}
// Example REST API endpoint implementation
public static async Task<string> HandleApiRequest(string jsonRequest)
{
var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest);
var editor = new InteractiveExcelEditor();
return await editor.ProcessEditRequestAsync(request);
}
}
using IronXL;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
public class InteractiveExcelEditor
{
public class EditRequest
{
public string FileName { get; set; }
public string WorksheetName { get; set; }
public Dictionary<string, object> CellUpdates { get; set; }
public List<RangeUpdate> RangeUpdates { get; set; }
}
public class RangeUpdate
{
public string Range { get; set; }
public object Value { get; set; }
public CellStyle Style { get; set; }
}
public class CellStyle
{
public string BackgroundColor { get; set; }
public bool Bold { get; set; }
public string NumberFormat { get; set; }
}
public async Task<string> ProcessEditRequestAsync(EditRequest request)
{
try
{
// Load workbook
WorkBook workBook = WorkBook.Load(request.FileName);
WorkSheet sheet = string.IsNullOrEmpty(request.WorksheetName)
? workBook.DefaultWorkSheet
: workBook.GetWorkSheet(request.WorksheetName);
// Process individual cell updates
if (request.CellUpdates != null)
{
foreach (var update in request.CellUpdates)
{
var cell = sheet[update.Key];
cell.Value = update.Value;
// Auto-detect and apply appropriate formatting
if (update.Value is decimal || update.Value is double)
{
cell.FormatString = "#,##0.00";
}
else if (update.Value is DateTime)
{
cell.FormatString = "yyyy-MM-dd";
}
}
}
// Process range updates
if (request.RangeUpdates != null)
{
foreach (var rangeUpdate in request.RangeUpdates)
{
var range = sheet[rangeUpdate.Range];
range.Value = rangeUpdate.Value;
// Apply styling if provided
if (rangeUpdate.Style != null)
{
if (!string.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor))
range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor;
if (rangeUpdate.Style.Bold)
range.Style.Font.Bold = true;
if (!string.IsNullOrEmpty(rangeUpdate.Style.NumberFormat))
range.FormatString = rangeUpdate.Style.NumberFormat;
}
}
}
// Generate unique output filename
string outputFile = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}";
workBook.SaveAs(outputFile);
return outputFile;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to process edit request: {ex.Message}", ex);
}
}
// Example REST API endpoint implementation
public static async Task<string> HandleApiRequest(string jsonRequest)
{
var request = System.Text.Json.JsonSerializer.Deserialize<EditRequest>(jsonRequest);
var editor = new InteractiveExcelEditor();
return await editor.ProcessEditRequestAsync(request);
}
}
Imports IronXL
Imports System
Imports System.Collections.Generic
Imports System.Threading.Tasks
Public Class InteractiveExcelEditor
Public Class EditRequest
Public Property FileName As String
Public Property WorksheetName As String
Public Property CellUpdates As Dictionary(Of String, Object)
Public Property RangeUpdates As List(Of RangeUpdate)
End Class
Public Class RangeUpdate
Public Property Range As String
Public Property Value As Object
Public Property Style As CellStyle
End Class
Public Class CellStyle
Public Property BackgroundColor As String
Public Property Bold As Boolean
Public Property NumberFormat As String
End Class
Public Async Function ProcessEditRequestAsync(request As EditRequest) As Task(Of String)
Try
' Load workbook
Dim workBook As WorkBook = WorkBook.Load(request.FileName)
Dim sheet As WorkSheet = If(String.IsNullOrEmpty(request.WorksheetName), workBook.DefaultWorkSheet, workBook.GetWorkSheet(request.WorksheetName))
' Process individual cell updates
If request.CellUpdates IsNot Nothing Then
For Each update In request.CellUpdates
Dim cell = sheet(update.Key)
cell.Value = update.Value
' Auto-detect and apply appropriate formatting
If TypeOf update.Value Is Decimal OrElse TypeOf update.Value Is Double Then
cell.FormatString = "#,##0.00"
ElseIf TypeOf update.Value Is DateTime Then
cell.FormatString = "yyyy-MM-dd"
End If
Next
End If
' Process range updates
If request.RangeUpdates IsNot Nothing Then
For Each rangeUpdate In request.RangeUpdates
Dim range = sheet(rangeUpdate.Range)
range.Value = rangeUpdate.Value
' Apply styling if provided
If rangeUpdate.Style IsNot Nothing Then
If Not String.IsNullOrEmpty(rangeUpdate.Style.BackgroundColor) Then
range.Style.BackgroundColor = rangeUpdate.Style.BackgroundColor
End If
If rangeUpdate.Style.Bold Then
range.Style.Font.Bold = True
End If
If Not String.IsNullOrEmpty(rangeUpdate.Style.NumberFormat) Then
range.FormatString = rangeUpdate.Style.NumberFormat
End If
End If
Next
End If
' Generate unique output filename
Dim outputFile As String = $"edited_{DateTime.Now:yyyyMMddHHmmss}_{request.FileName}"
workBook.SaveAs(outputFile)
Return outputFile
Catch ex As Exception
Throw New InvalidOperationException($"Failed to process edit request: {ex.Message}", ex)
End Try
End Function
' Example REST API endpoint implementation
Public Shared Async Function HandleApiRequest(jsonRequest As String) As Task(Of String)
Dim request = System.Text.Json.JsonSerializer.Deserialize(Of EditRequest)(jsonRequest)
Dim editor = New InteractiveExcelEditor()
Return Await editor.ProcessEditRequestAsync(request)
End Function
End Class
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
その他のExcel自動化リソース
Excelの自動化機能を拡張するには、以下の専門リソースをご活用ください。
高度な機能を探る
IronXLは、基本的な細胞編集機能にとどまらず、幅広い機能を提供します。
- WebベースのExcel処理のためのBlazorアプリケーションでのExcelの操作
- よりクリーンなデプロイメントのために、 Interopを使用しないExcel操作
- .NETでExcelファイルをゼロから作成する
- データベース統合のためのExcelからSQLへの変換
- クロスプラットフォームのモバイルアプリ向けに.NET MAUI上で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処理に必要なツールを提供します。 レポート生成とデータ処理タスクを簡素化するために、これらのパターンを今日からワークフローに実装し始めましょう。
よくある質問
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"; の構文を使って複数のセルに値を割り当てることができます。ここで ws は WorkSheet オブジェクトです。
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 のウェブサイトをご覧ください。



