Como Selecionar Intervalos em Planilha Excel com C# e IronXL
O IronXL permite que desenvolvedores C# selecionem e manipulem intervalos, linhas e colunas ao ler arquivo Excel ou editar planilha Excel, sem depender do Office Interop. Use uma sintaxe simples como workSheet["A1:C3"] para selecionar intervalos, GetRow() para linhas e GetColumn() para colunas programaticamente.
Início rápido: Selecionando um intervalo de células no IronXL em uma única linha
Use uma única chamada para GetRange em uma planilha do IronXL para selecionar um intervalo retangular como "A1:C3" — sem loops, sem complicações. É a maneira mais rápida de começar a manipular várias células ao mesmo tempo.
-
Instale IronXL com o Gerenciador de Pacotes NuGet
PM > Install-Package IronXL.Excel -
Copie e execute este trecho de código.
var range = workSheet.GetRange("A1:C3"); -
Implante para testar em seu ambiente de produção.
Comece a usar IronXL em seu projeto hoje com uma avaliação gratuita
Fluxo de trabalho mínimo (5 etapas)
- Baixe a biblioteca C# para selecionar o intervalo.
- Use **a coluna `workSheet["A2:B8"]`** diretamente após o objeto `WorkSheet` para selecionar um intervalo de células.
- Utilize o método `GetRow` para selecionar uma linha de uma planilha.
- Selecione uma coluna da planilha fornecida usando o método `GetColumn`
- Combine intervalos facilmente com o operador '+'.
Como faço para selecionar diferentes tipos de fogões no IronXL?
Com o IronXL, você pode realizar diversas operações em intervalos selecionados, como classificação , cálculos e agregações. A biblioteca fornece métodos intuitivos para seleção de intervalos que espelham a funcionalidade nativa do Excel, ao mesmo tempo que oferece controle programático.
A seleção de intervalo constitui a base para muitas operações do Excel. Seja para realizar cálculos matemáticos , aplicar formatação ou extrair dados, selecionar as células corretas é o primeiro passo. O IronXL simplifica esse processo com sua API flexível de seleção de intervalo.
Como faço para selecionar um intervalo retangular de células?
Para selecionar um intervalo de células da célula A2 à célula B8, você pode usar o seguinte código:
:path=/static-assets/excel/content-code-examples/how-to/select-range-range.cs
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"];
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")
Trabalhando com faixas selecionadas
Após selecionar um intervalo, o IronXL oferece diversas operações que você pode realizar:
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}");
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}");
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}")
Para operações mais complexas em planilhas, consulte a documentação completa da API .
Como faço para selecionar uma linha inteira?
Para selecionar a 4ª linha, você pode usar o método GetRow(3) com indexação baseada em zero. Isso incluirá todas as células da 4ª linha, mesmo que algumas células correspondentes em outras linhas estejam vazias.
:path=/static-assets/excel/content-code-examples/how-to/select-range-row.cs
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);
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)
A seleção de linhas é particularmente útil quando você precisa processar dados linha por linha. Por exemplo, ao carregar dados de planilha para análise:
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();
}
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();
}
Imports IronXL
Imports System
Imports System.Linq
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
Como faço para selecionar uma coluna inteira?
Para selecionar a coluna C, você pode usar o método GetColumn(2) ou especificar o endereço do intervalo como workSheet["C:C"]. Assim como o método GetRow, ele incluirá todas as células relevantes, estejam elas preenchidas na coluna especificada ou não.
:path=/static-assets/excel/content-code-examples/how-to/select-range-column.cs
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);
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)
A seleção de colunas se mostra extremamente útil ao trabalhar com dados em formato de coluna, como relatórios financeiros ou exportações de banco de dados. Você pode utilizá-lo ao criar novas planilhas com colunas calculadas:
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");
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");
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")
Como combinar vários intervalos?
IronXL oferece a flexibilidade de combinar vários objetos IronXL.Ranges.Range usando o operador '+'. Ao usar o operador '+', você pode facilmente concatenar ou mesclar intervalos para criar um novo intervalo. Essa funcionalidade é particularmente útil quando você precisa aplicar operações a células não contíguas. Para técnicas avançadas de combinação, veja o exemplo de combinação de intervalos do Excel .
range será modificada para incluir os intervalos combinados.
:path=/static-assets/excel/content-code-examples/how-to/select-range-combine-range.cs
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"];
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")
Técnicas avançadas de seleção de alcance
O IronXL oferece suporte a cenários sofisticados de seleção de intervalo que espelham os recursos do Excel:
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;
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;
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
Ao trabalhar com fórmulas , a seleção de intervalo torna-se ainda mais poderosa:
// 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();
// 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();
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()
Melhores práticas para seleção de alcance
Ao trabalhar com fogões no IronXL, considere estas dicas de desempenho e confiabilidade:
-
Utilize endereços de intervalo específicos quando souber exatamente quais células são necessárias. Isso é mais eficiente do que selecionar linhas ou colunas inteiras.
- Valide os limites do intervalo antes da seleção para evitar erros de tempo de execução:
// 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 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 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
- Aproveite a iteração de intervalo para um processamento eficiente:
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
}
}
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 batches
For Each cell In dataRange
If cell.IsNumeric Then
cell.Value = CType(cell.Value, Decimal) * 1.1D ' 10% increase
End If
Next
Para cenários mais complexos, como copiar intervalos de células , o IronXL oferece métodos especializados que preservam a formatação e as fórmulas.
Primeiros passos com o IronXL
Para começar a usar os recursos de seleção de alcance do IronXL em seus projetos, consulte o guia completo de primeiros passos . Instale o IronXL através do Gerenciador de Pacotes NuGet:
Install-Package IronXL.Excel
Ou usando a CLI do .NET:
dotnet add package IronXL.Excel
dotnet add package IronXL.Excel
A seleção de intervalo constitui a base da manipulação do Excel em C#. Com a API intuitiva do IronXL, você pode selecionar, manipular e transformar dados do Excel de forma eficiente, sem a complexidade do Office Interop. Seja para criar relatórios, analisar dados ou automatizar tarefas em planilhas, dominar a seleção de intervalos aumentará significativamente sua produtividade.
Perguntas frequentes
Como selecionar um intervalo de células no Excel usando C#?
Com o IronXL, você pode selecionar um intervalo de células usando uma sintaxe simples como workSheet["A1:C3"] ou workSheet.GetRange("A1:C3"). Isso permite selecionar intervalos retangulares sem a necessidade de dependências do Office Interop.
Posso selecionar linhas e colunas inteiras programaticamente?
Sim, o IronXL oferece os métodos GetRow() e GetColumn() para selecionar linhas e colunas inteiras em sua planilha do Excel. Esses métodos oferecem controle programático sobre a seleção de linhas e colunas sem a necessidade de instalar o Excel.
Como faço para combinar vários intervalos de células em C#?
O IronXL permite combinar vários intervalos usando o operador '+'. Esse recurso facilita o trabalho programático com seleções de células não contíguas.
Que operações posso realizar em intervalos selecionados?
Depois de selecionar um intervalo com o IronXL, você pode realizar diversas operações, incluindo classificação, cálculos matemáticos, aplicação de formatação, iteração entre células e agregação de dados, como o cálculo de somas.
Como faço para aplicar formatação a um intervalo selecionado?
Após selecionar um intervalo no IronXL, você pode aplicar formatação usando a propriedade Estilo. Por exemplo, você pode definir cores de fundo com `range.Style.BackgroundColor` e deixar o texto em negrito com `range.Style.Font.Bold = true`.
Posso iterar pelas células em um intervalo selecionado?
Sim, o IronXL permite iterar pelas células em um intervalo selecionado usando um loop foreach. Cada célula fornece acesso ao seu valor e endereço, facilitando o processamento de dados célula por célula.

