# C#でExcelの範囲を選択する方法
IronXLはC#開発者がOffice Interopに依存することなくExcelの範囲、行、列を選択、操作することを可能にします。 範囲を選択するには`GetColumn()`をプログラム的に使用します。
*as-heading:2(クイックスタート: IronXL で 1 行でセル範囲を選択する)*
IronXLのワークシート上で`GetRange`を1回呼び出すだけで、"A1:C3"のような長方形の範囲を取得できます。ループも手間もありません。 複数のセルを一度に操作する最速の方法です。
```cs
:title=Quick & Easy Range Selection with IronXL
var range = workSheet.GetRange("A1:C3");
```
<div class="hsg-featured-snippet">
<h3>最小限のワークフロー(5ステップ)</h3>
<ol>
<li>範囲を選択するためのC#ライブラリをダウンロードする</li>
<li><a class="js-modal-open" data-modal-id="trial-license-after-download" href="https://nuget.org/packages/IronXL.Excel/">ワークシートオブジェクトの<code>WorkSheet["A2:B8"]</code>を直接使用してセル範囲を選択します</a></li>
<li><code>GetRow</code>メソッドを使用してワークシートの行を選択します</li>
<li><code>GetColumn</code>メソッドを使用して、指定されたワークシートの列を選択します。</li>
<li><code>+</code>演算子を使用して範囲を簡単に組み合わせます</li>
</ol>
</div>
<br class="clear" />
## IronXLで異なる種類の範囲を選択するにはどうすればよいですか?
IronXL.Excelでは、[ソート](https://ironsoftware.com/csharp/excel/how-to/sort-cells/)、計算、集計など、選択した範囲に対してさまざまな操作を行うことができます。 このライブラリは、Excelのネイティブ機能を反映しつつ、プログラムによる制御を提供する範囲選択のための直感的なメソッドを提供します。
範囲選択はExcelの多くの操作の基礎となります。 [数学的計算](https://ironsoftware.com/csharp/excel/how-to/math-functions/)を実行する場合でも、書式を適用する場合でも、データを抽出する場合でも、正しいセルを選択することが最初のステップです。IronXLは柔軟な範囲選択APIによってこのプロセスを簡単にします。
[[i:(セルの値を変更または移動するメソッドを適用すると、影響を受ける範囲、行、または列の値がそれに応じて更新されます。)]]
`+`演算子を使用して複数組み合わせることができます。
### 長方形のセル範囲を選択するにはどうすればよいですか?
セル`B8`までの範囲を選択するには、以下のコードを使用できます。
```csharp
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get range from worksheet
var range = workSheet["A2:B8"];
```
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/excel/how-to/select-range/select-range-range.png" alt="B2:C8の範囲をピンク色でハイライトしたスプレッドシート。" class="img-responsive add-shadow" />
</div>
</div>
### 選択した範囲での作業
一度範囲を選択すると、IronXLは実行できる多くの操作を提供します:
```csharp
using IronXL;
using System;
using System.Linq;
// Load an existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Select a range and perform operations
var range = workSheet["A1:C5"];
// Apply formatting to the entire range
range.Style.BackgroundColor = "#E8F5E9";
range.Style.Font.Bold = true;
// Iterate through cells in the range
foreach (var cell in range)
{
Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}");
}
// Get sum of numeric values in the range
decimal sum = range.Sum();
Console.WriteLine($"Sum of range: {sum}");
```
スプレッドシートのより複雑な操作については、[包括的な API ドキュメント](https://ironsoftware.com/csharp/excel/object-reference/api/)を参照してください。
### 行全体を選択するにはどうすればよいですか?
4番目の行を選択するには、ゼロベースのインデックスを使用して`GetRow(3)`メソッドを使用できます。 これは、他の行の対応するセルが空であっても、4行目のすべてのセルを含みます。
```csharp
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get row from worksheet
var row = workSheet.GetRow(3);
```
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/excel/how-to/select-range/select-range-row.png" alt="行4が選択されたスプレッドシート。行選択を示すため、セルB4からF4の周囲に赤枠が表示されている。" class="img-responsive add-shadow" />
</div>
</div>
行選択は、データを一行ずつ処理する必要がある場合に特に便利です。例えば、[分析のためにスプレッドシートデータをロードする](https://ironsoftware.com/csharp/excel/how-to/load-spreadsheet/)ときなどです:
```csharp
using IronXL;
using System;
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Process each row
for (int i = 0; i < workSheet.RowCount; i++)
{
var row = workSheet.GetRow(i);
// Skip empty rows
if (row.IsEmpty) continue;
// Process row data
foreach (var cell in row)
{
// Your processing logic here
Console.Write($"{cell.Value}\t");
}
Console.WriteLine();
}
```
### 列全体を選択するにはどうすればよいですか?
列Cを選択するには、`workSheet["C:C"]`と指定します。 `GetRow`メソッドと同様に、指定された列内に埋まっているかどうかにかかわらず、すべての関連するセルを含めます。
```csharp
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get column from worksheet
var column = workSheet.GetColumn(2);
```
<div class="content-img-align-center">
<div class="center-image-wrapper">
<img src="/static-assets/excel/how-to/select-range/select-range-column.png" alt="範囲選択の例で列全体を選択する方法を示す、C#列が赤くハイライトされたスプレッドシート" class="img-responsive add-shadow" />
</div>
</div>
[[t:(すべての行と列のインデックス位置はゼロベースのインデックスに従います。)]]
列の選択は、財務報告書やデータベースのエクスポートのような列データを扱う際に非常に有用です。 [計算列のある新しいスプレッドシート](https://ironsoftware.com/csharp/excel/how-to/create-spreadsheet/)を作成するときに使用するかもしれません:
```csharp
using IronXL;
using System;
// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Data");
// Add header row
workSheet["A1"].Value = "Quantity";
workSheet["B1"].Value = "Price";
workSheet["C1"].Value = "Total";
// Add sample data
for (int i = 2; i <= 10; i++)
{
workSheet[$"A{i}"].Value = i - 1;
workSheet[$"B{i}"].Value = 10.5 * (i - 1);
}
// Select the Total column and apply formula
var totalColumn = workSheet.GetColumn(2); // Column C
for (int i = 2; i <= 10; i++)
{
workSheet[$"C{i}"].Formula = $"=A{i}*B{i}";
}
workBook.SaveAs("calculations.xlsx");
```
### 複数の範囲を結合するにはどうすればよいですか?
IronXLは、複数の`+`演算子を使って組み合わせる柔軟性を提供します。 `+`演算子を使用することで、範囲を簡単に連結またはマージして新しい範囲を作成できます。 この機能は、連続しないセルに操作を適用する必要がある場合に特に便利です。 高度な結合テクニックについては、[combining Excel ranges example](https://ironsoftware.com/csharp/excel/examples/combine-excel-ranges/)を参照してください。
`+`演算子を使用して行と列を直接組み合わせることはサポートされていません。
[[i:(範囲を結合すると、元の範囲が変更されます。 以下のコードスニペットで、変数`range`が結合された範囲を含むように変更されます。
)]]
```csharp
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get range from worksheet
var range = workSheet["A2:B2"];
// Combine two ranges
var combinedRange = range + workSheet["A5:B5"];
```
### 高度な範囲選択テクニック
IronXLはExcelの機能を反映した高度な範囲選択シナリオをサポートしています:
```csharp
using IronXL;
using System;
using System.Linq;
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Select multiple non-adjacent ranges
var headerRange = workSheet["A1:E1"];
var dataRange1 = workSheet["A5:E10"];
var dataRange2 = workSheet["A15:E20"];
// Combine ranges for batch operations
var combinedData = dataRange1 + dataRange2;
// Apply consistent formatting across combined ranges
combinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
combinedData.Style.Font.Height = 11;
// Copy formatting from one range to another
var sourceFormat = headerRange.Style;
dataRange1.First().Style = sourceFormat;
```
[数式を扱う](https://ironsoftware.com/csharp/excel/how-to/edit-formulas/)とき、範囲選択はさらに強力になります:
```csharp
// Select a range for formula application
var calculationRange = workSheet["D2:D20"];
// Apply formulas that reference other ranges
for (int i = 2; i <= 20; i++)
{
workSheet[$"D{i}"].Formula = $"=SUM(A{i}:C{i})";
}
// Use range in aggregate functions
var sumRange = workSheet["B2:B20"];
decimal totalSum = sumRange.Sum();
decimal average = sumRange.Avg();
decimal max = sumRange.Max();
```
### レンジ選択のベストプラクティス
IronXLで範囲を扱う際には、パフォーマンスと信頼性のヒントを考慮してください:
1.**必要なセルが正確に分かっている場合は、特定の範囲アドレス**を使用してください。 これは、行や列全体を選択するよりも効率的です。
2.**実行時エラーを避けるために、選択する前に範囲の境界を検証してください**:
```csharp
// Check if range exists before selection
int lastRow = workSheet.RowCount;
int lastColumn = workSheet.ColumnCount;
if (lastRow >= 10 && lastColumn >= 3)
{
var safeRange = workSheet["A1:C10"];
// Process range
}
```
3.**範囲反復**を活用して、効率的に処理してください:
```csharp
var dataRange = workSheet["A1:E100"];
// Efficient: Process in batches
foreach (var cell in dataRange)
{
if (cell.IsNumeric)
{
cell.Value = (decimal)cell.Value * 1.1; // 10% increase
}
}
```
[セル範囲のコピー](https://ironsoftware.com/csharp/excel/how-to/copy-cells/)のような複雑なシナリオのために、IronXLは書式と数式を維持する特別なメソッドを提供します。
### IronXLを使い始める
あなたのプロジェクトでIronXL.Excelのさまざまな選択機能を使い始めるには、[包括的なスタートガイド](https://ironsoftware.com/csharp/excel/docs/)から始めてください。 NuGetパッケージマネージャ経由でIronXLをインストールしてください:
```shell
:ProductInstall
```
または.NET CLIを使用して:
```shell
:InstallCmd dotnet add package IronXL.Excel
```
範囲選択は、C#でのExcel操作の基礎を形成します。 IronXLの直感的なAPIを使えば、Office Interopのような複雑な操作なしに、Excelデータの選択、操作、変換を効率的に行うことができます。レポートの作成、データ分析、表計算作業の自動化など、範囲選択をマスターすることで生産性が大幅に向上します。
using IronXL;using System.Linq;WorkBook workBook = WorkBook.Load("sample.xls");WorkSheet workSheet = workBook.WorkSheets.First();// Get range from worksheetvar range = workSheet["A2:B8"];
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get range from worksheet
var range = workSheet["A2:B8"];
ImportsIronXLImportsSystem.LinqPrivate workBook AsWorkBook = WorkBook.Load("sample.xls")Private workSheet AsWorkSheet = workBook.WorkSheets.First()' Get range from worksheetPrivate range = workSheet("A2:B8")
Imports IronXL
Imports System.Linq
Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Get range from worksheet
Private range = workSheet("A2:B8")
選択した範囲での作業
一度範囲を選択すると、IronXLは実行できる多くの操作を提供します:
using IronXL;using System;using System.Linq;// Load an existing spreadsheetWorkBook workBook = WorkBook.Load("sample.xlsx");WorkSheet workSheet = workBook.WorkSheets.First();// Select a range and perform operationsvar range = workSheet["A1:C5"];// Apply formatting to the entire rangerange.Style.BackgroundColor = "#E8F5E9";range.Style.Font.Bold = true;// Iterate through cells in the rangeforeach (var cell in range){Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}");}// Get sum of numeric values in the rangedecimal sum = range.Sum();Console.WriteLine($"Sum of range: {sum}");
using IronXL;
using System;
using System.Linq;
// Load an existing spreadsheet
WorkBook workBook = WorkBook.Load("sample.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Select a range and perform operations
var range = workSheet["A1:C5"];
// Apply formatting to the entire range
range.Style.BackgroundColor = "#E8F5E9";
range.Style.Font.Bold = true;
// Iterate through cells in the range
foreach (var cell in range)
{
Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}");
}
// Get sum of numeric values in the range
decimal sum = range.Sum();
Console.WriteLine($"Sum of range: {sum}");
ImportsIronXLImportsSystemImportsSystem.Linq' Load an existing spreadsheetDim workBook AsWorkBook = WorkBook.Load("sample.xlsx")Dim workSheet AsWorkSheet = workBook.WorkSheets.First()' Select a range and perform operationsDim range = workSheet("A1:C5")' Apply formatting to the entire rangerange.Style.BackgroundColor = "#E8F5E9"range.Style.Font.Bold = True' Iterate through cells in the rangeFor Each cell In rangeConsole.WriteLine($"Cell {cell.AddressString}: {cell.Value}")Next' Get sum of numeric values in the rangeDim sum AsDecimal = range.Sum()Console.WriteLine($"Sum of range: {sum}")
Imports IronXL
Imports System
Imports System.Linq
' Load an existing spreadsheet
Dim workBook As WorkBook = WorkBook.Load("sample.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' Select a range and perform operations
Dim range = workSheet("A1:C5")
' Apply formatting to the entire range
range.Style.BackgroundColor = "#E8F5E9"
range.Style.Font.Bold = True
' Iterate through cells in the range
For Each cell In range
Console.WriteLine($"Cell {cell.AddressString}: {cell.Value}")
Next
' Get sum of numeric values in the range
Dim sum As Decimal = range.Sum()
Console.WriteLine($"Sum of range: {sum}")
using IronXL;using System.Linq;WorkBook workBook = WorkBook.Load("sample.xls");WorkSheet workSheet = workBook.WorkSheets.First();// Get row from worksheetvar row = workSheet.GetRow(3);
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get row from worksheet
var row = workSheet.GetRow(3);
ImportsIronXLImportsSystem.LinqPrivate workBook AsWorkBook = WorkBook.Load("sample.xls")Private workSheet AsWorkSheet = workBook.WorkSheets.First()' Get row from worksheetPrivate row = workSheet.GetRow(3)
Imports IronXL
Imports System.Linq
Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Get row from worksheet
Private row = workSheet.GetRow(3)
using IronXL;using System;WorkBook workBook = WorkBook.Load("data.xlsx");WorkSheet workSheet = workBook.WorkSheets.First();// Process each rowfor (int i = 0; i < workSheet.RowCount; i++){ var row = workSheet.GetRow(i); // Skip empty rows if (row.IsEmpty) continue; // Process row data foreach (var cell in row) { // Your processing logic hereConsole.Write($"{cell.Value}\t"); }Console.WriteLine();}
using IronXL;
using System;
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Process each row
for (int i = 0; i < workSheet.RowCount; i++)
{
var row = workSheet.GetRow(i);
// Skip empty rows
if (row.IsEmpty) continue;
// Process row data
foreach (var cell in row)
{
// Your processing logic here
Console.Write($"{cell.Value}\t");
}
Console.WriteLine();
}
ImportsIronXLImportsSystemDim workBook AsWorkBook = WorkBook.Load("data.xlsx")Dim workSheet AsWorkSheet = workBook.WorkSheets.First()' Process each rowFor i AsInteger = 0 To workSheet.RowCount - 1 Dim row = workSheet.GetRow(i) ' Skip empty rows If row.IsEmptyThen Continue For ' Process row data For Each cell In row ' Your processing logic hereConsole.Write($"{cell.Value}" & vbTab) NextConsole.WriteLine()Next
Imports IronXL
Imports System
Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' Process each row
For i As Integer = 0 To workSheet.RowCount - 1
Dim row = workSheet.GetRow(i)
' Skip empty rows
If row.IsEmpty Then Continue For
' Process row data
For Each cell In row
' Your processing logic here
Console.Write($"{cell.Value}" & vbTab)
Next
Console.WriteLine()
Next
using IronXL;using System.Linq;WorkBook workBook = WorkBook.Load("sample.xls");WorkSheet workSheet = workBook.WorkSheets.First();// Get column from worksheetvar column = workSheet.GetColumn(2);
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get column from worksheet
var column = workSheet.GetColumn(2);
ImportsIronXLImportsSystem.LinqPrivate workBook AsWorkBook = WorkBook.Load("sample.xls")Private workSheet AsWorkSheet = workBook.WorkSheets.First()' Get column from worksheetPrivate column = workSheet.GetColumn(2)
Imports IronXL
Imports System.Linq
Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Get column from worksheet
Private column = workSheet.GetColumn(2)
using IronXL;using System;// Create a new workbookWorkBook workBook = WorkBook.Create();WorkSheet workSheet = workBook.CreateWorkSheet("Data");// Add header rowworkSheet["A1"].Value = "Quantity";workSheet["B1"].Value = "Price";workSheet["C1"].Value = "Total";// Add sample datafor (int i = 2; i <= 10; i++){ workSheet[$"A{i}"].Value = i - 1; workSheet[$"B{i}"].Value = 10.5 * (i - 1);}// Select the Total column and apply formulavar totalColumn = workSheet.GetColumn(2); // Column Cfor (int i = 2; i <= 10; i++){ workSheet[$"C{i}"].Formula = $"=A{i}*B{i}";}workBook.SaveAs("calculations.xlsx");
using IronXL;
using System;
// Create a new workbook
WorkBook workBook = WorkBook.Create();
WorkSheet workSheet = workBook.CreateWorkSheet("Data");
// Add header row
workSheet["A1"].Value = "Quantity";
workSheet["B1"].Value = "Price";
workSheet["C1"].Value = "Total";
// Add sample data
for (int i = 2; i <= 10; i++)
{
workSheet[$"A{i}"].Value = i - 1;
workSheet[$"B{i}"].Value = 10.5 * (i - 1);
}
// Select the Total column and apply formula
var totalColumn = workSheet.GetColumn(2); // Column C
for (int i = 2; i <= 10; i++)
{
workSheet[$"C{i}"].Formula = $"=A{i}*B{i}";
}
workBook.SaveAs("calculations.xlsx");
ImportsIronXLImportsSystem' Create a new workbookDim workBook AsWorkBook = WorkBook.Create()Dim workSheet AsWorkSheet = workBook.CreateWorkSheet("Data")' Add header rowworkSheet("A1").Value = "Quantity"workSheet("B1").Value = "Price"workSheet("C1").Value = "Total"' Add sample dataFor i AsInteger = 2 To 10 workSheet($"A{i}").Value = i - 1 workSheet($"B{i}").Value = 10.5 * (i - 1)Next' Select the Total column and apply formulaDim totalColumn = workSheet.GetColumn(2) ' Column CFor i AsInteger = 2 To 10 workSheet($"C{i}").Formula = $"=A{i}*B{i}"NextworkBook.SaveAs("calculations.xlsx")
Imports IronXL
Imports System
' Create a new workbook
Dim workBook As WorkBook = WorkBook.Create()
Dim workSheet As WorkSheet = workBook.CreateWorkSheet("Data")
' Add header row
workSheet("A1").Value = "Quantity"
workSheet("B1").Value = "Price"
workSheet("C1").Value = "Total"
' Add sample data
For i As Integer = 2 To 10
workSheet($"A{i}").Value = i - 1
workSheet($"B{i}").Value = 10.5 * (i - 1)
Next
' Select the Total column and apply formula
Dim totalColumn = workSheet.GetColumn(2) ' Column C
For i As Integer = 2 To 10
workSheet($"C{i}").Formula = $"=A{i}*B{i}"
Next
workBook.SaveAs("calculations.xlsx")
using IronXL;using System.Linq;WorkBook workBook = WorkBook.Load("sample.xls");WorkSheet workSheet = workBook.WorkSheets.First();// Get range from worksheetvar range = workSheet["A2:B2"];// Combine two rangesvar combinedRange = range + workSheet["A5:B5"];
using IronXL;
using System.Linq;
WorkBook workBook = WorkBook.Load("sample.xls");
WorkSheet workSheet = workBook.WorkSheets.First();
// Get range from worksheet
var range = workSheet["A2:B2"];
// Combine two ranges
var combinedRange = range + workSheet["A5:B5"];
ImportsIronXLImportsSystem.LinqPrivate workBook AsWorkBook = WorkBook.Load("sample.xls")Private workSheet AsWorkSheet = workBook.WorkSheets.First()' Get range from worksheetPrivate range = workSheet("A2:B2")' Combine two rangesPrivate combinedRange = range + workSheet("A5:B5")
Imports IronXL
Imports System.Linq
Private workBook As WorkBook = WorkBook.Load("sample.xls")
Private workSheet As WorkSheet = workBook.WorkSheets.First()
' Get range from worksheet
Private range = workSheet("A2:B2")
' Combine two ranges
Private combinedRange = range + workSheet("A5:B5")
高度な範囲選択テクニック
IronXLはExcelの機能を反映した高度な範囲選択シナリオをサポートしています:
using IronXL;using System;using System.Linq;WorkBook workBook = WorkBook.Load("data.xlsx");WorkSheet workSheet = workBook.WorkSheets.First();// Select multiple non-adjacent rangesvar headerRange = workSheet["A1:E1"];var dataRange1 = workSheet["A5:E10"];var dataRange2 = workSheet["A15:E20"];// Combine ranges for batch operationsvar combinedData = dataRange1 + dataRange2;// Apply consistent formatting across combined rangescombinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;combinedData.Style.Font.Height = 11;// Copy formatting from one range to anothervar sourceFormat = headerRange.Style;dataRange1.First().Style = sourceFormat;
using IronXL;
using System;
using System.Linq;
WorkBook workBook = WorkBook.Load("data.xlsx");
WorkSheet workSheet = workBook.WorkSheets.First();
// Select multiple non-adjacent ranges
var headerRange = workSheet["A1:E1"];
var dataRange1 = workSheet["A5:E10"];
var dataRange2 = workSheet["A15:E20"];
// Combine ranges for batch operations
var combinedData = dataRange1 + dataRange2;
// Apply consistent formatting across combined ranges
combinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin;
combinedData.Style.Font.Height = 11;
// Copy formatting from one range to another
var sourceFormat = headerRange.Style;
dataRange1.First().Style = sourceFormat;
ImportsIronXLImportsSystemImportsSystem.LinqDim workBook AsWorkBook = WorkBook.Load("data.xlsx")Dim workSheet AsWorkSheet = workBook.WorkSheets.First()' Select multiple non-adjacent rangesDim headerRange = workSheet("A1:E1")Dim dataRange1 = workSheet("A5:E10")Dim dataRange2 = workSheet("A15:E20")' Combine ranges for batch operationsDim combinedData = dataRange1 + dataRange2' Apply consistent formatting across combined rangescombinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.ThincombinedData.Style.Font.Height = 11' Copy formatting from one range to anotherDim sourceFormat = headerRange.StyledataRange1.First().Style = sourceFormat
Imports IronXL
Imports System
Imports System.Linq
Dim workBook As WorkBook = WorkBook.Load("data.xlsx")
Dim workSheet As WorkSheet = workBook.WorkSheets.First()
' Select multiple non-adjacent ranges
Dim headerRange = workSheet("A1:E1")
Dim dataRange1 = workSheet("A5:E10")
Dim dataRange2 = workSheet("A15:E20")
' Combine ranges for batch operations
Dim combinedData = dataRange1 + dataRange2
' Apply consistent formatting across combined ranges
combinedData.Style.BottomBorder.Type = IronXL.Styles.BorderType.Thin
combinedData.Style.Font.Height = 11
' Copy formatting from one range to another
Dim sourceFormat = headerRange.Style
dataRange1.First().Style = sourceFormat
// Select a range for formula applicationvar calculationRange = workSheet["D2:D20"];// Apply formulas that reference other rangesfor (int i = 2; i <= 20; i++){ workSheet[$"D{i}"].Formula = $"=SUM(A{i}:C{i})";}// Use range in aggregate functionsvar sumRange = workSheet["B2:B20"];decimal totalSum = sumRange.Sum();decimal average = sumRange.Avg();decimal max = sumRange.Max();
// Select a range for formula application
var calculationRange = workSheet["D2:D20"];
// Apply formulas that reference other ranges
for (int i = 2; i <= 20; i++)
{
workSheet[$"D{i}"].Formula = $"=SUM(A{i}:C{i})";
}
// Use range in aggregate functions
var sumRange = workSheet["B2:B20"];
decimal totalSum = sumRange.Sum();
decimal average = sumRange.Avg();
decimal max = sumRange.Max();
ImportsSystem' Select a range for formula applicationDim calculationRange = workSheet("D2:D20")' Apply formulas that reference other rangesFor i AsInteger = 2 To 20 workSheet($"D{i}").Formula = $"=SUM(A{i}:C{i})"Next' Use range in aggregate functionsDim sumRange = workSheet("B2:B20")Dim totalSum AsDecimal = sumRange.Sum()Dim average AsDecimal = sumRange.Avg()Dim max AsDecimal = sumRange.Max()
Imports System
' Select a range for formula application
Dim calculationRange = workSheet("D2:D20")
' Apply formulas that reference other ranges
For i As Integer = 2 To 20
workSheet($"D{i}").Formula = $"=SUM(A{i}:C{i})"
Next
' Use range in aggregate functions
Dim sumRange = workSheet("B2:B20")
Dim totalSum As Decimal = sumRange.Sum()
Dim average As Decimal = sumRange.Avg()
Dim max As Decimal = sumRange.Max()
// Check if range exists before selectionint lastRow = workSheet.RowCount;int lastColumn = workSheet.ColumnCount;if (lastRow >= 10 && lastColumn >= 3){ var safeRange = workSheet["A1:C10"]; // Process range}
// Check if range exists before selection
int lastRow = workSheet.RowCount;
int lastColumn = workSheet.ColumnCount;
if (lastRow >= 10 && lastColumn >= 3)
{
var safeRange = workSheet["A1:C10"];
// Process range
}
' Check if range exists before selectionDim lastRow AsInteger = workSheet.RowCountDim lastColumn AsInteger = workSheet.ColumnCountIf lastRow >= 10AndAlso lastColumn >= 3 Then Dim safeRange = workSheet("A1:C10") ' Process rangeEnd If
' Check if range exists before selection
Dim lastRow As Integer = workSheet.RowCount
Dim lastColumn As Integer = workSheet.ColumnCount
If lastRow >= 10 AndAlso lastColumn >= 3 Then
Dim safeRange = workSheet("A1:C10")
' Process range
End If
3.範囲反復を活用して、効率的に処理してください:
var dataRange = workSheet["A1:E100"];// Efficient: Process in batchesforeach (var cell in dataRange){ if (cell.IsNumeric) { cell.Value = (decimal)cell.Value * 1.1; // 10% increase }}
var dataRange = workSheet["A1:E100"];
// Efficient: Process in batches
foreach (var cell in dataRange)
{
if (cell.IsNumeric)
{
cell.Value = (decimal)cell.Value * 1.1; // 10% increase
}
}
Dim dataRange = workSheet("A1:E100")' Efficient: Process in batchesFor Each cell In dataRange If cell.IsNumericThen cell.Value = CType(cell.Value, Decimal) * 1.1D ' 10% increase End IfNext
Dim dataRange = workSheet("A1:E100")
' Efficient: Process in batches
For Each cell In dataRange
If cell.IsNumeric Then
cell.Value = CType(cell.Value, Decimal) * 1.1D ' 10% increase
End If
Next
What is the benefit of using range selection in IronXL for Excel operations?
Range selection with IronXL simplifies operations like sorting, formatting, and aggregations by allowing developers to easily target specific cells or areas in a worksheet without complex code.
How does IronXL differ from Office Interop when selecting Excel ranges?
Unlike Office Interop, IronXL provides a lightweight and dependency-free approach to Excel manipulation in C#, enhancing performance and simplifying deployment without needing Microsoft Office installed on the server.
What are some advanced range selection techniques available in IronXL?
IronXL offers advanced techniques such as combining multiple ranges, applying consistent formatting, and using ranges in formulas for dynamic calculations and batch data processing.
How should I start using IronXL for range selection in my C# projects?
To start using IronXL for range selection, install it via NuGet Package Manager or .NET CLI, and refer to the getting started guide to explore its straightforward API for Excel data manipulation.