Java'da Excel Dosyası Nasıl Okunur (Eğitim)
Excel Nedir?
Microsoft Excel Çalışma Kitabı, kullanıcılarının verileri verimli bir şekilde organize etmesine ve saklamasına olanak tanıyan bir elektronik tablo tabanlı yazılımdır. Verileri, satır ve sütunları kullanarak tablosal bir biçimde saklar ve düzenler. Excel elektronik tablosundaki hücre, verileri tutan bir kutudur ve çeşitli stiller, biçimlendirme ve formüllerle değiştirilebilir.
Excel Dosyaları Java'da Nasıl Okunur?
Bir Excel dosyasını okumak bazen karmaşık olabilir. Java'da Excel dosyalarını okumak, Excel hücreleri nedeniyle Java'da Word dosyalarını okumaktan biraz farklıdır. JDK, Microsoft Excel belgelerini okumak veya yazmak için doğrudan bir API sağlamaz. Bunun yerine, üçüncü taraf kütüphane olan Apache POI'ye güvenmemiz gerekir.
Apache POI Kutuphanesi
POI, "Kötü Gizleme Uygulaması" anlamına gelir. Apache POI, Microsoft belgelerini okumak ve yazmak için tasarlanmış açık kaynaklı bir Java kütüphanesidir. Microsoft Office'e dayalı çeşitli dosya formatlarını oluşturmak ve manipüle etmek için bir yol sunar. Apache POI kullanarak, bir kişinin Microsoft Office dosya formatları üzerinde oluşturma, değiştirme ve görüntüleme/okuma işlemleri yapabilmesi gerekir.
Apache POI Kütüphanesini İndirin ve Kurun
Başlamak için, POI JAR'larının en son sürümünü indireceğiz. http://poi.apache.org/download.html adresine gidin ve Java'da bir Excel dosyasını okumak için Java API'sini içeren en son ZIP dosyasını indirin.
Apache POI JAR Dosyalarını İndir
ZIP dosyasını indirdiğinizde, onu açmanız ve aşağıdaki JAR dosyalarını projenizin sınıf yoluna eklemeniz gerekir. Bu, aşağıda Bir Excel Dosyasından Okuma kısmında açıklanmaktadır.
Apache POI Jar Dosyalarını Java classpath'ine ekleyin
Not: lib ve ooxml-lib dosyalarıyla birlikte diğer dosyaları da kopyalayın.
POI'deki Sınıflar ve Arayüzler
Aşağıdakiler, kullanılabilecek XLS ve XLSX dosya formatlarını destekleyen sınıflardır:
Apache POI Sınıfları
Aşağıda Java'da XLS ve XLSX dosyalarını okumak için POI içindeki farklı Java arayüzleri ve sınıflarının bir listesi bulunmaktadır:
Workbook arayüzü, HSSFWorkbook ve XSSFWorkbook sınıfları tarafından uygulanmaktadır:
- HSSFWorkbook: Bu, bir XLS dosyasının sınıf temsilidir.
- XSSFWorkbook: Bu, bir XLSX dosyasının sınıf temsilidir.
Sheet arayüzü, HSSFSheet ve XSSFSheet sınıfları tarafından uygulanmaktadır:
- HSSFSheet: Bu, bir XLS dosyasındaki bir sayfanın sınıf temsilidir.
- XSSFSheet: Bu, bir XLSX dosyasındaki bir sayfanın sınıf temsilidir.
Row arayüzü, HSSFRow ve XSSFRow sınıfları tarafından uygulanmaktadır:
- HSSFRow: Bu, bir XLS dosyasındaki bir sayfanın satırının sınıf temsilidir.
- XSSFRow: Bu, bir XLSX dosyasındaki bir sayfanın satırının sınıf temsilidir.
Cell arayüzü, HSSFCell ve XSSFCell sınıfları tarafından uygulanmaktadır:
- HSSFCell: Bu, bir XLS dosyasındaki satırın bir hücresinin sınıf temsilidir.
- XSSFCell: Bu, bir XLSX dosyasındaki satırın bir hücresinin sınıf temsilidir.
Excel Dosyasından Okuma
Örnek olarak, Java'da aşağıdaki Excel dosyasını okuyacağız:
Okunacak Excel Dosyası
Java'da Excel Dosyası Okuma Adımları
- Herhangi bir Java IDE kullanarak bir Java projesi oluşturun. Bu proje için Netbeans kullanacağız.
- Ardından, projede bir
libklasörü oluşturun. - Sonra, indirilen JAR dosyalarını önceki adımda oluşturulan
libklasörüne ekleyin. Class-Pathayarlayın: Proje klasörüne sağ tıklayın > Derleme Yolu > Dış JAR dosyaları Ekle > yukarıdaki tüm JAR dosyalarını seçin > Uygula ve kapat.- Şimdi, ReadExcelFileDemo adında bir sınıf dosyası oluşturalım.
- "studentdata.xls" adında bir Excel dosyası oluşturun ve yukarıdaki verileri veya herhangi bir veriyi içine yazın.
Aşağıda, Java'da Excel dosyalarını okuma ile ilgili bir kod örneği bulunmaktadır:
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();
}
}
Çıktı:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
XLSX dosyalarını okuma adımları da aynı, ancak aşağıdaki iki ana nokta hariç:
- İlk olarak, dosya formatını .xlsx olarak değiştirin. Aynı "studentdata" dosyası kullanılabilir, ancak .xlsx uzantısıyla.
- İkincisi, Java Apache POI'yi nasıl ithal ettiğimiz konusunda bir fark var. Kod şu şekildedir:
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();
}
}
}
Çıktı:
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
Id Names
1 Zeeshan
2 Shoaib
3 Umar
4 Rizwan
5 Ahsan
IronXL C# Kutuphanesi
IronXL, Microsoft Excel belgelerini C# ile okumayı ve düzenlemeyi kolaylaştıran bağımsız bir .NET kutuphanesidir. Ne Microsoft Excel'in kurulu olmasını gerektirir ne de Interop'a bağımlı olur.
IronXL kullanarak, geliştiriciler yalnızca birkaç satır kod yazarak ve hızlı performansla tüm Excel ile ilgili hesaplamaları zahmetsizce gerçekleştirebilir. Bu, iki hücre eklemek, bir sütunun toplamını hesaplamak, bir Excel tablosuna tüm sütunu eklemek, bir Excel tablosuna tüm satırı eklemek, tek ve çok satırlı sütun toplamaları gibi işler için ya da IronXL'in yardımcı özellikleri sayesinde kolaylaştırılan diğer birçok görev için olabilir.
IronXL, .NET Framework, .NET Core, Mobil, Xamarin, Azure Linux ve macOS'u tamamen destekler.
IronXL Özellik Seti
- XLS/XLSX/CSV/TSV'den veri yükleme, okuma ve düzenleme.
- XLS/XLSX/CSV/TSV/JSON'a kaydetme ve ihraç etme.
System.DataNesneleri — Excel E-Tabloları ileSystem.Data.DataSetveSystem.Data.DataTablenesneleri olarak çalışın.- Formüller — Excel formülleri ile çalışır.
- Aralıklar — ["A1:B10"] sözdizimi kullanımı kolay.
- Sıralama — satırları, sütunları ve aralıkları sıralayın.
- Stil — görsel stiller, yazı tipi ve yazı tipi boyutu, arka plan deseni, kenarlık, hizalama ve sayı formatları.
Aşağıda, IronXL kullanarak C#'da Excel dosyası okuma ile ilgili bir kod örneği bulunmaktadır:
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
IronXL ile çalışmak bir geliştiricinin işini çok daha kolay hale getirir. Basit ve kolay kullanılabilen kodu, yazılım hatalarını azaltırken Excel dosyalarıyla çalışmayı sağlar.
IronXL'yi İndirin ve projelerinizde hemen kullanın.




