Como ler um arquivo Excel em Java (Tutorial)
O que é Excel?
O Microsoft Excel Workbook é um software baseado em planilha que permite aos seus usuários organizar e armazenar dados de forma eficiente. Armazena e organiza dados em forma tabular, ou seja, usando linhas e colunas. A célula em uma planilha do Excel é a caixa que contém dados e pode ser manipulada com diferentes estilos, formatação e fórmulas.
Como Ler Arquivos Excel em Java?
Ler um arquivo Excel pode ser complicado às vezes. Ler arquivos Excel em Java também é um pouco diferente de ler arquivos Word em Java por causa das células do Excel. O JDK não fornece uma API direta para ler ou escrever documentos Microsoft Excel. Em vez disso, temos que contar com a biblioteca de terceiros Apache POI.
Biblioteca Apache POI
POI significa "Implementação de Ofuscação Pobre". Apache POI é uma biblioteca Java de código aberto projetada para leitura e escrita de documentos Microsoft. Ele oferece uma maneira de criar e manipular vários formatos de arquivo baseados no Microsoft Office. Usando o Apache POI, deve-se ser capaz de criar, modificar e exibir/ler operações em uma gama de formatos de arquivo do Microsoft Office.
Baixar e Instalar a biblioteca Apache POI
Para começar, vamos baixar a versão mais recente dos JARs do POI. Navegue até http://poi.apache.org/download.html e baixe o arquivo ZIP mais recente, que conterá a API Java para ler um arquivo Excel em Java.
Baixar Arquivos JAR do Apache POI
Quando você baixar o arquivo ZIP, será necessário descompactá-lo e adicionar os seguintes arquivos JAR ao classpath do seu projeto. Isso está explicado em Lendo de um Arquivo Excel abaixo.
Adicione os arquivos Jar do Apache POI ao classpath do Java
Nota: Também copie os arquivos de lib e ooxml-lib junto com os outros arquivos.
Classes e Interfaces no POI
A seguir estão as classes suportadas para os formatos de arquivo XLS e XLSX que podem ser usadas:
Classes Apache POI
A seguir está uma lista de diferentes interfaces e classes Java no POI para ler arquivos XLS e XLSX em Java:
A interface Workbook é implementada pelas classes HSSFWorkbook e XSSFWorkbook:
- HSSFWorkbook: Esta é uma representação de classe do arquivo XLS.
- XSSFWorkbook: Esta é uma representação de classe do arquivo XLSX.
A interface Sheet é implementada pelas classes HSSFSheet e XSSFSheet:
- HSSFSheet: Esta é uma classe que representa uma planilha em um arquivo XLS.
- XSSFSheet: Esta é uma classe que representa uma planilha em um arquivo XLSX.
A interface Row é implementada pelas classes HSSFRow e XSSFRow:
- HSSFRow: Esta é uma classe que representa uma linha na planilha de um arquivo XLS.
- XSSFRow: Esta é uma classe que representa uma linha na planilha de um arquivo XLSX.
A interface Cell é implementada pelas classes HSSFCell e XSSFCell:
- HSSFCell: Esta é uma classe que representa uma célula em uma linha de um arquivo XLS.
- XSSFCell: Esta é uma classe que representa uma célula em uma linha de um arquivo XLSX.
Lendo de um Arquivo Excel
Para nosso exemplo, vamos ler o seguinte arquivo Excel em Java:
O Arquivo Excel que será Lido
Etapas para Ler Arquivo Excel em Java
- Crie um projeto Java usando qualquer IDE Java. Nós usaremos o Netbeans para este projeto.
- Em seguida, crie uma pasta
libno projeto. - Depois, adicione os arquivos JAR baixados à pasta
libcriada na etapa anterior. - Configure o
Class-Pathclicando com o botão direito na pasta Project > Build Path > Add External JARs files > selecione todos os arquivos JAR acima > Apply e close. - Agora, vamos criar um arquivo de classe com o nome ReadExcelFileDemo.
- Crie um arquivo Excel com o nome "studentdata.xls" e escreva os dados acima ou quaisquer dados nele.
Abaixo está o exemplo de código para ler arquivos Excel em Java:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
public class ReadExcelFileDemo {
public static void main(String[] args) throws IOException {
// Obtain input bytes from a file
FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));
// Creating workbook instance that refers to .xls file
HSSFWorkbook wb = new HSSFWorkbook(fis);
// Creating a Sheet object to retrieve the object
HSSFSheet sheet = wb.getSheetAt(0);
// Evaluating cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for (Row row : sheet) {
for (Cell cell : row) {
switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println();
}
// Closing the workbook to free resources
wb.close();
}
}
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
public class ReadExcelFileDemo {
public static void main(String[] args) throws IOException {
// Obtain input bytes from a file
FileInputStream fis = new FileInputStream(new File("C:\\demo\\studentdata.xls"));
// Creating workbook instance that refers to .xls file
HSSFWorkbook wb = new HSSFWorkbook(fis);
// Creating a Sheet object to retrieve the object
HSSFSheet sheet = wb.getSheetAt(0);
// Evaluating cell type
FormulaEvaluator formulaEvaluator = wb.getCreationHelper().createFormulaEvaluator();
for (Row row : sheet) {
for (Cell cell : row) {
switch (formulaEvaluator.evaluateInCell(cell).getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println();
}
// Closing the workbook to free resources
wb.close();
}
}
Saída:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
As etapas são as mesmas para ler arquivos XLSX, exceto pelos dois pontos principais abaixo:
- Primeiramente, altere o formato do arquivo para .xlsx. O mesmo arquivo "studentdata" pode ser usado, mas com a extensão .xlsx.
- Em segundo lugar, há uma diferença em como importamos o Apache POI Java. O código é o seguinte:
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XLSXReaderExample {
public static void main(String[] args) {
try {
File file = new File("C:\\demo\\studentdata.xlsx");
FileInputStream fis = new FileInputStream(file);
// Creating Workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
// Iterating over rows using iterator
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column in a row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
// Closing the workbook to free resources
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class XLSXReaderExample {
public static void main(String[] args) {
try {
File file = new File("C:\\demo\\studentdata.xlsx");
FileInputStream fis = new FileInputStream(file);
// Creating Workbook instance that refers to .xlsx file
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheetAt(0);
// Iterating over rows using iterator
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext()) {
Row row = itr.next();
// Iterating over each column in a row
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case NUMERIC: // Field that represents numeric cell type
// Getting the value of the cell as a number
System.out.print(cell.getNumericCellValue() + "\t\t");
break;
case STRING: // Field that represents string cell type
// Getting the value of the cell as a string
System.out.print(cell.getStringCellValue() + "\t\t");
break;
}
}
System.out.println("");
}
// Closing the workbook to free resources
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Saída:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
A Biblioteca IronXL C
IronXL é uma biblioteca .NET independente que facilita a leitura e edição de documentos do Microsoft Excel com C#. Não requer que o Microsoft Excel esteja instalado, nem depende do Interop.
Usando IronXL, os desenvolvedores podem realizar todos os cálculos relacionados ao Excel de maneira fácil, escrevendo apenas algumas linhas de código e com desempenho rápido. Isso pode ser para tarefas como adicionar duas células, calcular o total geral de uma coluna, adicionar uma coluna inteira a uma tabela Excel, adicionar uma linha inteira a uma tabela Excel, somas de coluna de uma ou várias linhas, ou muitas outras tarefas facilitadas através dos recursos úteis do IronXL.
IronXL suporta completamente o .NET Framework, .NET Core, Mobile, Xamarin, Azure Linux e macOS.
Conjunto de Recursos do IronXL
- Carregar, ler e editar dados de XLS/XLSX/CSV/TSV.
- Salvar e exportar para XLS/XLSX/CSV/TSV/JSON.
- Objetos
System.Data— trabalhar com Planilhas Excel como objetosSystem.Data.DataSeteSystem.Data.DataTable. - Fórmulas — funciona com fórmulas Excel.
- Intervalos — a sintaxe ["A1:B10"] é fácil de usar.
- Ordenação — classificar linhas, colunas e intervalos.
- Estilização — estilos visuais, fonte e tamanho da fonte, padrão de fundo, borda, alinhamento e formatos numéricos.
Abaixo está um exemplo de código para ler um arquivo Excel em C# usando IronXL:
using IronXL;
using System.Linq;
public class ExcelReaderExample
{
public static void Main(string[] args)
{
// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
// Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly
foreach (var cell in sheet["A2:A10"]) {
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
}
}
using IronXL;
using System.Linq;
public class ExcelReaderExample
{
public static void Main(string[] args)
{
// Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
WorkBook workbook = WorkBook.Load("test.xlsx");
WorkSheet sheet = workbook.WorkSheets.First();
// Select cells easily in Excel notation and return the calculated value
int cellValue = sheet["A2"].IntValue;
// Read from Ranges of cells elegantly
foreach (var cell in sheet["A2:A10"]) {
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text);
}
}
}
Imports IronXL
Imports System.Linq
Public Class ExcelReaderExample
Public Shared Sub Main(ByVal args() As String)
' Supported spreadsheet formats for reading include: XLSX, XLS, CSV and TSV
Dim workbook As WorkBook = WorkBook.Load("test.xlsx")
Dim sheet As WorkSheet = workbook.WorkSheets.First()
' Select cells easily in Excel notation and return the calculated value
Dim cellValue As Integer = sheet("A2").IntValue
' Read from Ranges of cells elegantly
For Each cell In sheet("A2:A10")
Console.WriteLine("Cell {0} has value '{1}'", cell.AddressString, cell.Text)
Next cell
End Sub
End Class
Trabalhar com IronXL torna o trabalho de um desenvolvedor muito mais fácil. Seu código simples e fácil de usar torna o software menos propenso a erros ao trabalhar com arquivos Excel.
Baixe o IronXL e use-o em seus projetos hoje.




