Como ler arquivos do Excel em C#

How to Read Excel Files in C# Without Interop: Complete Developer Guide

This article was translated from English: Does it need improvement?
Translated
View the article in English

Domine a manipulação de arquivos Excel em C# usando o IronXL — a poderosa biblioteca .NET que lê, valida e exporta dados de planilhas sem a necessidade de instalar o Microsoft Office. Este tutorial completo demonstra operações práticas do Excel, incluindo validação de dados, conversão de banco de dados e integração com API REST.

Início rápido: Leia uma célula com IronXL em uma única linha

Com apenas uma linha de código, você pode carregar uma planilha do Excel e recuperar o valor de uma célula usando o IronXL. Foi projetado para ser fácil de usar — ​​sem interoperabilidade, sem configurações complexas — apenas acesso rápido aos seus dados.

  1. Instale IronXL com o Gerenciador de Pacotes NuGet

    PM > Install-Package IronXl.Excel
  2. Copie e execute este trecho de código.

    var value = IronXl.WorkBook.Load("file.xlsx").GetWorkSheet(0)["A1"].StringValue;
  3. Implante para testar em seu ambiente de produção.

    Comece a usar IronXL em seu projeto hoje com uma avaliação gratuita

    arrow pointer

Como configuro o IronXL para ler arquivos Excel em C#?

Configurar o IronXL para ler arquivos Excel em seu projeto C# leva apenas alguns minutos. A biblioteca suporta os formatos .XLS e .XLSX, tornando-a versátil para qualquer tarefa relacionada ao Excel.

Siga estes passos para começar:

  1. Baixe a biblioteca C# para ler arquivos do Excel.
  2. Carregar e ler planilhas do Excel usando WorkBook.Load()
  3. Acesse as planilhas com o método GetWorkSheet()
  4. Leia os valores das células usando uma sintaxe intuitiva como sheet["A1"].Value
  5. Validar e processar dados de planilhas programaticamente
  6. Exportar dados para bancos de dados usando o Entity Framework

IronXL se destaca na leitura e edição de documentos do Microsoft Excel com C#. A biblioteca funciona de forma independente — não requer o Microsoft Excel nem o Interop para funcionar. Na verdade, o IronXL oferece uma API mais rápida e intuitiva do que o Microsoft.Office.Interop.Excel .

IronXL inclui:

  • Suporte técnico especializado por parte dos nossos engenheiros .NET
  • Instalação fácil via Microsoft Visual Studio
  • Teste experimental gratuito para desenvolvimento. Licenças de liteLicense

A leitura e a criação de arquivos Excel em C# e VB.NET tornam-se simples com o uso da biblioteca de software IronXL.

Como ler arquivos Excel .XLS e .XLSX usando o IronXL

Aqui está o fluxo de trabalho essencial para ler arquivos do Excel usando o IronXL:

  1. Instale a biblioteca IronXL Excel através do pacote NuGet ou baixe a DLL do Excel for .NET.
  2. Use o método WorkBook.Load() para ler qualquer documento XLS, XLSX ou CSV.
  3. Acesse os valores das células usando uma sintaxe intuitiva: sheet["A11"].DecimalValue
:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-1.cs
using IronXL;
using System;
using System.Linq;

// Load Excel workbook from file path
WorkBook workBook = WorkBook.Load("test.xlsx");

// Access the first worksheet using LINQ
WorkSheet workSheet = workBook.WorkSheets.First();

// Read integer value from cell A2
int cellValue = workSheet["A2"].IntValue;
Console.WriteLine($"Cell A2 value: {cellValue}");

// Iterate through a range of cells
foreach (var cell in workSheet["A2:A10"])
{
    Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}

// Advanced Operations with LINQ
// Calculate sum using built_in Sum() method
decimal sum = workSheet["A2:A10"].Sum();

// Find maximum value using LINQ
decimal max = workSheet["A2:A10"].Max(c => c.DecimalValue);

// Output calculated results
Console.WriteLine($"Sum of A2:A10: {sum}");
Console.WriteLine($"Maximum value: {max}");
$vbLabelText   $csharpLabel

Este código demonstra vários recursos importantes do IronXL: carregamento de planilhas, acesso a células por endereço, iteração por intervalos e realização de cálculos. O método WorkBook.Load() detecta formatos de arquivo de forma inteligente, enquanto a sintaxe de intervalo ["A2:A10"] fornece seleção de células semelhante ao Excel. A integração com LINQ permite consultas e agregações de dados poderosas em coleções de células.

Os exemplos de código neste tutorial funcionam com três planilhas do Excel de exemplo que demonstram diferentes cenários de dados:

Três planilhas do Excel exibidas no Solution Explorer do Visual Studio Arquivos Excel de exemplo (GDP.xlsx, People.xlsx e PopulationByState.xlsx) usados ​​ao longo deste tutorial para demonstrar várias operações do IronXL.


Como posso instalar a biblioteca IronXL em C#?


A instalação da biblioteca IronXl.Excel adiciona funcionalidades abrangentes do Excel aos seus projetos .NET Framework . Escolha entre a instalação via NuGet ou a integração manual de DLLs.

Instalando o pacote NuGet IronXL

  1. No Visual Studio, clique com o botão direito do mouse no seu projeto e selecione "Gerenciar Pacotes NuGet..."
  2. Procure por "IronXl.Excel" na guia Procurar.
  3. Clique no botão Instalar para adicionar o IronXL ao seu projeto.

 Interface do Gerenciador de Pacotes NuGet mostrando a instalação do pacote IronXl.Excel A instalação do IronXL através do Gerenciador de Pacotes NuGet do Visual Studio proporciona o gerenciamento automático de dependências.

Alternativamente, instale o IronXL usando o Console do Gerenciador de Pacotes:

  1. Abra o Console do Gerenciador de Pacotes (Ferramentas → Gerenciador de Pacotes NuGet → Console do Gerenciador de Pacotes)
  2. Execute o comando de instalação:
Install-Package IronXl.Excel

Você também pode visualizar os detalhes do pacote no site do NuGet .

Instalação manual

Para instalação manual, baixe a DLL IronXL .NET Excel e faça referência a ela diretamente em seu projeto do Visual Studio.

Como faço para carregar e ler uma planilha do Excel?

A classe WorkBook representa um arquivo Excel completo. Carregue arquivos Excel usando o método WorkBook.Load(), que aceita caminhos de arquivos nos formatos XLS, XLSX, CSV e TSV.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-2.cs
using IronXL;
using System;
using System.Linq;

// Load Excel file from specified path
WorkBook workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");

Console.WriteLine("Workbook loaded successfully.");

// Access specific worksheet by name
WorkSheet sheet = workBook.GetWorkSheet("Sheet1");

// Read and display cell value
string cellValue = sheet["A1"].StringValue;
Console.WriteLine($"Cell A1 contains: {cellValue}");

// Perform additional operations
// Count non_empty cells in column A
int rowCount = sheet["A:A"].Count(cell => !cell.IsEmpty);
Console.WriteLine($"Column A has {rowCount} non_empty cells");
$vbLabelText   $csharpLabel

Cada WorkBook contém vários objetos WorkSheet que representam planilhas individuais do Excel. Acesse as planilhas pelo nome usando GetWorkSheet() :

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-3.cs
using IronXL;
using System;

// Get worksheet by name
WorkSheet workSheet = workBook.GetWorkSheet("GDPByCountry");

Console.WriteLine("Worksheet 'GDPByCountry' not found");
// List available worksheets
foreach (var sheet in workBook.WorkSheets)
{
    Console.WriteLine($"Available: {sheet.Name}");
}
$vbLabelText   $csharpLabel

Como faço para criar novos documentos do Excel em C#?

Crie novos documentos do Excel construindo um objeto WorkBook com o formato de arquivo desejado. O IronXL suporta os formatos XLSX modernos e XLS legados.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-4.cs
using IronXL;

// Create new XLSX workbook (recommended format)
WorkBook workBook = WorkBook.Create(ExcelFileFormat.XLSX);

// Set workbook metadata
workBook.Metadata.Author = "Your Application";
workBook.Metadata.Comments = "Generated by IronXL";

// Create new XLS workbook for legacy support
WorkBook legacyWorkBook = WorkBook.Create(ExcelFileFormat.XLS);

// Save the workbook
workBook.SaveAs("NewDocument.xlsx");
$vbLabelText   $csharpLabel

Nota: Utilize ExcelFileFormat.XLS somente quando for necessária compatibilidade com o Excel 2003 e versões anteriores.

Como posso adicionar planilhas a um documento do Excel?

Um IronXL WorkBook contém uma coleção de planilhas. Compreender essa estrutura ajuda na criação de arquivos Excel com várias planilhas.

Diagrama mostrando a Pasta de Trabalho contendo várias Planilhas Representação visual da estrutura WorkBook contendo múltiplos objetos WorkSheet no IronXL.

Crie novas planilhas usando CreateWorkSheet():

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-5.cs
using IronXL;

// Create multiple worksheets with descriptive names
WorkSheet summarySheet = workBook.CreateWorkSheet("Summary");
WorkSheet dataSheet = workBook.CreateWorkSheet("RawData");
WorkSheet chartSheet = workBook.CreateWorkSheet("Charts");

// Set the active worksheet
workBook.SetActiveTab(0); // Makes "Summary" the active sheet

// Access default worksheet (first sheet)
WorkSheet defaultSheet = workBook.DefaultWorkSheet;
$vbLabelText   $csharpLabel

Como faço para ler e editar os valores de uma célula?

Ler e editar uma única célula

Acesse células individuais através da propriedade de indexação da planilha. A classe Cell do IronXL fornece propriedades de valor fortemente tipadas.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-6.cs
using IronXL;
using System;
using System.Linq;

// Load workbook and get worksheet
WorkBook workBook = WorkBook.Load("test.xlsx");
WorkSheet workSheet = workBook.DefaultWorkSheet;

// Access cell B1
IronXL.Cell cell = workSheet["B1"].First();

// Read cell value with type safety
string textValue = cell.StringValue;
int intValue = cell.IntValue;
decimal decimalValue = cell.DecimalValue;
DateTime? dateValue = cell.DateTimeValue;

// Check cell data type
if (cell.IsNumeric)
{
    Console.WriteLine($"Numeric value: {cell.DecimalValue}");
}
else if (cell.IsText)
{
    Console.WriteLine($"Text value: {cell.StringValue}");
}
$vbLabelText   $csharpLabel

A classe Cell oferece múltiplas propriedades para diferentes tipos de dados, convertendo automaticamente os valores quando possível. Para mais informações sobre operações com células, consulte o tutorial de formatação de células .

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-7.cs
// Write different data types to cells
workSheet["A1"].Value = "Product Name";     // String
workSheet["B1"].Value = 99.95m;             // Decimal
workSheet["C1"].Value = DateTime.Today;     // Date
workSheet["D1"].Formula = "=B1*1.2";        // Formula
                                            // Format cells
workSheet["B1"].FormatString = "$#,##0.00"; // Currency format
workSheet["C1"].FormatString = "yyyy-MM-dd";// Date format
                                            // Save changes
workBook.Save();
$vbLabelText   $csharpLabel

Como posso trabalhar com intervalos de células?

A classe Range representa uma coleção de células, permitindo operações em lote em dados do Excel.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-8.cs
using IronXL;
using Range = IronXL.Range;

// Select range using Excel notation
Range range = workSheet["D2:D101"];

// Alternative: Use Range class for dynamic selection
Range dynamicRange = workSheet.GetRange("D2:D101"); // Row 2_101, Column D

// Perform bulk operations
range.Value = 0; // Set all cells to 0
$vbLabelText   $csharpLabel

Processa intervalos de forma eficiente usando loops quando a contagem de células é conhecida:

// Data validation example
public class ValidationResult
{
    public int Row { get; set; }
    public string PhoneError { get; set; }
    public string EmailError { get; set; }
    public string DateError { get; set; }
    public bool IsValid => string.IsNullOrEmpty(PhoneError) && 
                           string.IsNullOrEmpty(EmailError) && 
                           string.IsNullOrEmpty(DateError);
}

// Validate data in rows 2-101
var results = new List<ValidationResult>();

for (int row = 2; row <= 101; row++)
{
    var result = new ValidationResult { Row = row };

    // Get row data efficiently
    var phoneCell = workSheet[$"B{row}"];
    var emailCell = workSheet[$"D{row}"];
    var dateCell = workSheet[$"E{row}"];

    // Validate phone number
    if (!IsValidPhoneNumber(phoneCell.StringValue))
        result.PhoneError = "Invalid phone format";

    // Validate email
    if (!IsValidEmail(emailCell.StringValue))
        result.EmailError = "Invalid email format";

    // Validate date
    if (!dateCell.IsDateTime)
        result.DateError = "Invalid date format";

    results.Add(result);
}

// Helper methods
bool IsValidPhoneNumber(string phone) => 
    System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");

bool IsValidEmail(string email) => 
    email.Contains("@") && email.Contains(".");
// Data validation example
public class ValidationResult
{
    public int Row { get; set; }
    public string PhoneError { get; set; }
    public string EmailError { get; set; }
    public string DateError { get; set; }
    public bool IsValid => string.IsNullOrEmpty(PhoneError) && 
                           string.IsNullOrEmpty(EmailError) && 
                           string.IsNullOrEmpty(DateError);
}

// Validate data in rows 2-101
var results = new List<ValidationResult>();

for (int row = 2; row <= 101; row++)
{
    var result = new ValidationResult { Row = row };

    // Get row data efficiently
    var phoneCell = workSheet[$"B{row}"];
    var emailCell = workSheet[$"D{row}"];
    var dateCell = workSheet[$"E{row}"];

    // Validate phone number
    if (!IsValidPhoneNumber(phoneCell.StringValue))
        result.PhoneError = "Invalid phone format";

    // Validate email
    if (!IsValidEmail(emailCell.StringValue))
        result.EmailError = "Invalid email format";

    // Validate date
    if (!dateCell.IsDateTime)
        result.DateError = "Invalid date format";

    results.Add(result);
}

// Helper methods
bool IsValidPhoneNumber(string phone) => 
    System.Text.RegularExpressions.Regex.IsMatch(phone, @"^\d{3}-\d{3}-\d{4}$");

bool IsValidEmail(string email) => 
    email.Contains("@") && email.Contains(".");
$vbLabelText   $csharpLabel

Como adiciono fórmulas a planilhas do Excel?

Aplique fórmulas do Excel usando a propriedade Formula . O IronXL suporta a sintaxe padrão de fórmulas do Excel.

:path=/static-assets/excel/content-code-examples/tutorials/how-to-read-excel-file-csharp-9.cs
using IronXL;

// Add formulas to calculate percentages
int lastRow = 50;
for (int row = 2; row < lastRow; row++)
{
    // Calculate percentage: current value / total
    workSheet[$"C{row}"].Formula = $"=B{row}/B{lastRow}";
    // Format as percentage
    workSheet[$"C{row}"].FormatString = "0.00%";
}
// Add summary formulas
workSheet["B52"].Formula = "=SUM(B2:B50)";      // Sum
workSheet["B53"].Formula = "=AVERAGE(B2:B50)";   // Average
workSheet["B54"].Formula = "=MAX(B2:B50)";       // Maximum
workSheet["B55"].Formula = "=MIN(B2:B50)";       // Minimum
                                                 // Force formula evaluation
workBook.EvaluateAll();
$vbLabelText   $csharpLabel

Para editar fórmulas existentes, consulte o tutorial de fórmulas do Excel .

Como posso validar os dados de uma planilha?

O IronXL permite a validação completa de dados em planilhas. Este exemplo valida números de telefone, endereços de e-mail e datas usando bibliotecas externas e funcionalidades integradas do C#.

using System.Text.RegularExpressions;
using IronXL;

// Validation implementation
for (int i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get cells for current person
    var cells = workSheet[$"A{i}:E{i}"].ToList();

    // Validate phone (column B)
    string phone = cells[1].StringValue;
    if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
    {
        result.PhoneNumberErrorMessage = "Invalid phone format";
    }

    // Validate email (column D)
    string email = cells[3].StringValue;
    if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
    {
        result.EmailErrorMessage = "Invalid email address";
    }

    // Validate date (column E)
    if (!cells[4].IsDateTime)
    {
        result.DateErrorMessage = "Invalid date format";
    }
}
using System.Text.RegularExpressions;
using IronXL;

// Validation implementation
for (int i = 2; i <= 101; i++)
{
    var result = new PersonValidationResult { Row = i };
    results.Add(result);

    // Get cells for current person
    var cells = workSheet[$"A{i}:E{i}"].ToList();

    // Validate phone (column B)
    string phone = cells[1].StringValue;
    if (!Regex.IsMatch(phone, @"^\+?1?\d{10,14}$"))
    {
        result.PhoneNumberErrorMessage = "Invalid phone format";
    }

    // Validate email (column D)
    string email = cells[3].StringValue;
    if (!Regex.IsMatch(email, @"^[^@\s]+@[^@\s]+\.[^@\s]+$"))
    {
        result.EmailErrorMessage = "Invalid email address";
    }

    // Validate date (column E)
    if (!cells[4].IsDateTime)
    {
        result.DateErrorMessage = "Invalid date format";
    }
}
$vbLabelText   $csharpLabel

Salvar os resultados da validação em uma nova planilha:

// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");

// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";

// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF";

// Output validation results
for (int i = 0; i < results.Count; i++)
{
    var result = results[i];
    int outputRow = i + 2;

    resultsSheet[$"A{outputRow}"].Value = result.Row;
    resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
    resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
    resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";

    // Highlight invalid rows
    if (!result.IsValid)
    {
        resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
    }
}

// Auto-fit columns
for (int col = 0; col < 5; col++)
{
    resultsSheet.AutoSizeColumn(col);
}

// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
// Create results worksheet
var resultsSheet = workBook.CreateWorkSheet("ValidationResults");

// Add headers
resultsSheet["A1"].Value = "Row";
resultsSheet["B1"].Value = "Valid";
resultsSheet["C1"].Value = "Phone Error";
resultsSheet["D1"].Value = "Email Error";
resultsSheet["E1"].Value = "Date Error";

// Style headers
resultsSheet["A1:E1"].Style.Font.Bold = true;
resultsSheet["A1:E1"].Style.SetBackgroundColor("#4472C4");
resultsSheet["A1:E1"].Style.Font.Color = "#FFFFFF";

// Output validation results
for (int i = 0; i < results.Count; i++)
{
    var result = results[i];
    int outputRow = i + 2;

    resultsSheet[$"A{outputRow}"].Value = result.Row;
    resultsSheet[$"B{outputRow}"].Value = result.IsValid ? "Yes" : "No";
    resultsSheet[$"C{outputRow}"].Value = result.PhoneNumberErrorMessage ?? "";
    resultsSheet[$"D{outputRow}"].Value = result.EmailErrorMessage ?? "";
    resultsSheet[$"E{outputRow}"].Value = result.DateErrorMessage ?? "";

    // Highlight invalid rows
    if (!result.IsValid)
    {
        resultsSheet[$"A{outputRow}:E{outputRow}"].Style.SetBackgroundColor("#FFE6E6");
    }
}

// Auto-fit columns
for (int col = 0; col < 5; col++)
{
    resultsSheet.AutoSizeColumn(col);
}

// Save validated workbook
workBook.SaveAs(@"Spreadsheets\PeopleValidated.xlsx");
$vbLabelText   $csharpLabel

Como faço para exportar dados do Excel para um banco de dados?

Utilize o IronXL com o Entity Framework para exportar dados de planilhas diretamente para bancos de dados. Este exemplo demonstra como exportar dados do PIB de um país para o SQLite.

using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;

// Define entity model
public class Country
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();

    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Range(0, double.MaxValue)]
    public decimal GDP { get; set; }

    public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}
using System;
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore;
using IronXL;

// Define entity model
public class Country
{
    [Key]
    public Guid Id { get; set; } = Guid.NewGuid();

    [Required]
    [MaxLength(100)]
    public string Name { get; set; }

    [Range(0, double.MaxValue)]
    public decimal GDP { get; set; }

    public DateTime ImportedDate { get; set; } = DateTime.UtcNow;
}
$vbLabelText   $csharpLabel

Configure o contexto do Entity Framework para operações de banco de dados:

public class CountryContext : DbContext
{
    public DbSet<Country> Countries { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configure SQLite connection
        optionsBuilder.UseSqlite("Data Source=CountryGDP.db");

        // Enable sensitive data logging in development
        #if DEBUG
        optionsBuilder.EnableSensitiveDataLogging();
        #endif
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure decimal precision
        modelBuilder.Entity<Country>()
            .Property(c => c.GDP)
            .HasPrecision(18, 2);
    }
}
public class CountryContext : DbContext
{
    public DbSet<Country> Countries { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configure SQLite connection
        optionsBuilder.UseSqlite("Data Source=CountryGDP.db");

        // Enable sensitive data logging in development
        #if DEBUG
        optionsBuilder.EnableSensitiveDataLogging();
        #endif
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // Configure decimal precision
        modelBuilder.Entity<Country>()
            .Property(c => c.GDP)
            .HasPrecision(18, 2);
    }
}
$vbLabelText   $csharpLabel

ObserveNota: Para usar bancos de dados diferentes, instale o pacote NuGet apropriado (por exemplo, Microsoft.EntityFrameworkCore.SqlServer para SQL Server) e modifique a configuração de conexão de acordo.

Importar dados do Excel para o banco de dados:

using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;

public async Task ImportGDPDataAsync()
{
    try
    {
        // Load Excel file
        var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
        var workSheet = workBook.GetWorkSheet("GDPByCountry");

        using (var context = new CountryContext())
        {
            // Ensure database exists
            await context.Database.EnsureCreatedAsync();

            // Clear existing data (optional)
            await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");

            // Import data with progress tracking
            int totalRows = 213;
            for (int row = 2; row <= totalRows; row++)
            {
                // Read country data
                var countryName = workSheet[$"A{row}"].StringValue;
                var gdpValue = workSheet[$"B{row}"].DecimalValue;

                // Skip empty rows
                if (string.IsNullOrWhiteSpace(countryName))
                    continue;

                // Create and add entity
                var country = new Country
                {
                    Name = countryName.Trim(),
                    GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
                };

                await context.Countries.AddAsync(country);

                // Save in batches for performance
                if (row % 50 == 0)
                {
                    await context.SaveChangesAsync();
                    Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
                }
            }

            // Save remaining records
            await context.SaveChangesAsync();
            Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Import failed: {ex.Message}");
        throw;
    }
}
using System.Threading.Tasks;
using IronXL;
using Microsoft.EntityFrameworkCore;

public async Task ImportGDPDataAsync()
{
    try
    {
        // Load Excel file
        var workBook = WorkBook.Load(@"Spreadsheets\GDP.xlsx");
        var workSheet = workBook.GetWorkSheet("GDPByCountry");

        using (var context = new CountryContext())
        {
            // Ensure database exists
            await context.Database.EnsureCreatedAsync();

            // Clear existing data (optional)
            await context.Database.ExecuteSqlRawAsync("DELETE FROM Countries");

            // Import data with progress tracking
            int totalRows = 213;
            for (int row = 2; row <= totalRows; row++)
            {
                // Read country data
                var countryName = workSheet[$"A{row}"].StringValue;
                var gdpValue = workSheet[$"B{row}"].DecimalValue;

                // Skip empty rows
                if (string.IsNullOrWhiteSpace(countryName))
                    continue;

                // Create and add entity
                var country = new Country
                {
                    Name = countryName.Trim(),
                    GDP = gdpValue * 1_000_000 // Convert to actual value if in millions
                };

                await context.Countries.AddAsync(country);

                // Save in batches for performance
                if (row % 50 == 0)
                {
                    await context.SaveChangesAsync();
                    Console.WriteLine($"Imported {row - 1} of {totalRows} countries");
                }
            }

            // Save remaining records
            await context.SaveChangesAsync();
            Console.WriteLine($"Successfully imported {await context.Countries.CountAsync()} countries");
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine($"Import failed: {ex.Message}");
        throw;
    }
}
$vbLabelText   $csharpLabel

Como posso importar dados de API para planilhas do Excel?

Combine o IronXL com clientes HTTP para preencher planilhas com dados de API em tempo real. Este exemplo utiliza o RestClient.Net para obter dados de países.

using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;

// Define data model matching API response
public class RestCountry
{
    public string Name { get; set; }
    public long Population { get; set; }
    public string Region { get; set; }
    public string NumericCode { get; set; }
    public List<Language> Languages { get; set; }
}

public class Language
{
    public string Name { get; set; }
    public string NativeName { get; set; }
}

// Fetch and process API data
public async Task ImportCountryDataAsync()
{
    using var httpClient = new HttpClient();

    try
    {
        // Call REST API
        var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
        var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);

        // Create new workbook
        var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        var workSheet = workBook.CreateWorkSheet("Countries");

        // Add headers with styling
        string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
        for (int col = 0; col < headers.Length; col++)
        {
            var headerCell = workSheet[0, col];
            headerCell.Value = headers[col];
            headerCell.Style.Font.Bold = true;
            headerCell.Style.SetBackgroundColor("#366092");
            headerCell.Style.Font.Color = "#FFFFFF";
        }

        // Import country data
        await ProcessCountryData(countries, workSheet);

        // Save workbook
        workBook.SaveAs("CountriesFromAPI.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"API import failed: {ex.Message}");
    }
}
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;
using IronXL;

// Define data model matching API response
public class RestCountry
{
    public string Name { get; set; }
    public long Population { get; set; }
    public string Region { get; set; }
    public string NumericCode { get; set; }
    public List<Language> Languages { get; set; }
}

public class Language
{
    public string Name { get; set; }
    public string NativeName { get; set; }
}

// Fetch and process API data
public async Task ImportCountryDataAsync()
{
    using var httpClient = new HttpClient();

    try
    {
        // Call REST API
        var response = await httpClient.GetStringAsync("https://restcountries.com/v3.1/all");
        var countries = JsonConvert.DeserializeObject<List<RestCountry>>(response);

        // Create new workbook
        var workBook = WorkBook.Create(ExcelFileFormat.XLSX);
        var workSheet = workBook.CreateWorkSheet("Countries");

        // Add headers with styling
        string[] headers = { "Country", "Population", "Region", "Code", "Language 1", "Language 2", "Language 3" };
        for (int col = 0; col < headers.Length; col++)
        {
            var headerCell = workSheet[0, col];
            headerCell.Value = headers[col];
            headerCell.Style.Font.Bold = true;
            headerCell.Style.SetBackgroundColor("#366092");
            headerCell.Style.Font.Color = "#FFFFFF";
        }

        // Import country data
        await ProcessCountryData(countries, workSheet);

        // Save workbook
        workBook.SaveAs("CountriesFromAPI.xlsx");
    }
    catch (Exception ex)
    {
        Console.WriteLine($"API import failed: {ex.Message}");
    }
}
$vbLabelText   $csharpLabel

A API retorna dados JSON neste formato:

Estrutura de resposta JSON mostrando dados de países com matrizes de idiomas aninhadas Exemplo de resposta JSON da API REST Countries, mostrando informações hierárquicas sobre os países.

Processar e gravar os dados da API no Excel:

private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
    for (int i = 0; i < countries.Count; i++)
    {
        var country = countries[i];
        int row = i + 1; // Start from row 1 (after headers)

        // Write basic country data
        workSheet[$"A{row}"].Value = country.Name;
        workSheet[$"B{row}"].Value = country.Population;
        workSheet[$"C{row}"].Value = country.Region;
        workSheet[$"D{row}"].Value = country.NumericCode;

        // Format population with thousands separator
        workSheet[$"B{row}"].FormatString = "#,##0";

        // Add up to 3 languages
        for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
        {
            var language = country.Languages[langIndex];
            string columnLetter = ((char)('E' + langIndex)).ToString();
            workSheet[$"{columnLetter}{row}"].Value = language.Name;
        }

        // Add conditional formatting for regions
        if (country.Region == "Europe")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
        }
        else if (country.Region == "Asia")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
        }

        // Show progress every 50 countries
        if (i % 50 == 0)
        {
            Console.WriteLine($"Processed {i} of {countries.Count} countries");
        }
    }

    // Auto-size all columns
    for (int col = 0; col < 7; col++)
    {
        workSheet.AutoSizeColumn(col);
    }
}
private async Task ProcessCountryData(List<RestCountry> countries, WorkSheet workSheet)
{
    for (int i = 0; i < countries.Count; i++)
    {
        var country = countries[i];
        int row = i + 1; // Start from row 1 (after headers)

        // Write basic country data
        workSheet[$"A{row}"].Value = country.Name;
        workSheet[$"B{row}"].Value = country.Population;
        workSheet[$"C{row}"].Value = country.Region;
        workSheet[$"D{row}"].Value = country.NumericCode;

        // Format population with thousands separator
        workSheet[$"B{row}"].FormatString = "#,##0";

        // Add up to 3 languages
        for (int langIndex = 0; langIndex < Math.Min(3, country.Languages?.Count ?? 0); langIndex++)
        {
            var language = country.Languages[langIndex];
            string columnLetter = ((char)('E' + langIndex)).ToString();
            workSheet[$"{columnLetter}{row}"].Value = language.Name;
        }

        // Add conditional formatting for regions
        if (country.Region == "Europe")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#E6F3FF");
        }
        else if (country.Region == "Asia")
        {
            workSheet[$"C{row}"].Style.SetBackgroundColor("#FFF2E6");
        }

        // Show progress every 50 countries
        if (i % 50 == 0)
        {
            Console.WriteLine($"Processed {i} of {countries.Count} countries");
        }
    }

    // Auto-size all columns
    for (int col = 0; col < 7; col++)
    {
        workSheet.AutoSizeColumn(col);
    }
}
$vbLabelText   $csharpLabel

Referência de objetos e recursos

Explore a referência completa da API IronXL para obter documentação detalhada das classes e recursos avançados.

Tutoriais adicionais para operações no Excel:

Resumo

IronXl.Excel é uma biblioteca .NET abrangente para leitura e manipulação de arquivos Excel em diversos formatos. Ele funciona de forma independente, sem necessidade de instalação do Microsoft Excel ou do Interop.

Para manipulação de planilhas na nuvem, você também pode explorar a Biblioteca de Cliente da API do Google Sheets for .NET, que complementa os recursos de arquivos locais do IronXL.

Pronto para implementar a automação do Excel em seus projetos C#? Baixe o IronXL ou explore as opções de licenciamento para uso em produção.

Perguntas frequentes

Como posso ler arquivos do Excel em C# sem usar o Microsoft Office?

Você pode usar o IronXL para ler arquivos do Excel em C# sem precisar do Microsoft Office. O IronXL oferece métodos como WorkBook.Load() para abrir arquivos do Excel e permite acessar e manipular dados usando uma sintaxe intuitiva.

Quais formatos de arquivos do Excel podem ser lidos usando C#?

Com o IronXL, você pode ler arquivos nos formatos XLS e XLSX em C#. A biblioteca detecta automaticamente o formato do arquivo e o processa adequadamente usando o método WorkBook.Load() .

Como validar dados do Excel em C#?

IronXL permite validar dados do Excel programaticamente em C# iterando pelas células e aplicando lógica como expressões regulares para e-mails ou funções de validação personalizadas. Você pode gerar relatórios usando CreateWorkSheet() .

Como posso exportar dados do Excel para um banco de dados SQL usando C#?

Para exportar dados do Excel para um banco de dados SQL, use o IronXL para ler os dados do Excel com os métodos WorkBook.Load() e GetWorkSheet() , e então itere pelas células para transferir os dados para o seu banco de dados usando o Entity Framework.

Posso integrar a funcionalidade do Excel com aplicações ASP.NET Core?

Sim, o IronXL oferece suporte à integração com aplicativos ASP.NET Core. Você pode usar as classes WorkBook e WorkSheet em seus controladores para lidar com uploads de arquivos Excel, gerar relatórios e muito mais.

É possível adicionar fórmulas a planilhas do Excel usando C#?

O IronXL permite adicionar fórmulas a planilhas do Excel programaticamente. Você pode definir uma fórmula usando a propriedade Formula , como cell.Formula = "=SUM(A1:A10)" e calcular os resultados com workBook.EvaluateAll() .

Como faço para preencher arquivos do Excel com dados de uma API REST?

Para preencher arquivos do Excel com dados de uma API REST, use o IronXL juntamente com um cliente HTTP para buscar os dados da API e, em seguida, escreva-os no Excel usando métodos como sheet["A1"].Value . O IronXL gerencia a formatação e a estrutura do Excel.

Quais são as opções de licenciamento para usar bibliotecas do Excel em ambientes de produção?

A IronXL oferece um período de avaliação gratuito para fins de desenvolvimento, enquanto as licenças de produção começam em US$ 749. Essas licenças incluem suporte técnico dedicado e permitem a implantação em diversos ambientes sem a necessidade de licenças adicionais do Office.

Jacob Mellor, Diretor de Tecnologia da Team Iron
Diretor de Tecnologia

Jacob Mellor é Diretor de Tecnologia da Iron Software e um engenheiro visionário pioneiro na tecnologia C# PDF. Como desenvolvedor original do código-fonte principal da Iron Software, ele moldou a arquitetura de produtos da empresa desde sua criação, transformando-a, juntamente com o CEO Cameron Rimington, em uma ...

Leia mais

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 12
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/ready_to_started_202509.php
Line: 19
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 489
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Pronto para começar?
Nuget Downloads 1,890,100 | Versão: 2026.3 acaba de ser lançado

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 17
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

A PHP Error was encountered

Severity: Notice

Message: Undefined index: IronXl.Excel

Filename: helpers/counter_helper.php

Line Number: 85

Backtrace:

File: /var/www/ironpdf.com/application/helpers/counter_helper.php
Line: 85
Function: _error_handler

File: /var/www/ironpdf.com/application/views/main/sections/still_scrolling_202512.php
Line: 24
Function: getTotalDonwloadNumber

File: /var/www/ironpdf.com/application/views/products/sections/three_column_docs_page_structure.php
Line: 71
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/views/products/tutorials/index.php
Line: 2
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 88
Function: view

File: /var/www/ironpdf.com/application/libraries/Render.php
Line: 552
Function: view

File: /var/www/ironpdf.com/application/controllers/Products/Tutorials.php
Line: 29
Function: render_products_view

File: /var/www/ironpdf.com/index.php
Line: 292
Function: require_once

Still Scrolling Icon

Ainda está rolando a tela?

Quer provas rápidas? PM > Install-Package IronXl.Excel
executar um exemplo Veja seus dados se transformarem em uma planilha.