27 Kasım 2015 Cuma

Java Excel dosyası okuma

 import java.io.FileInputStream;  
 import java.io.IOException;  
 import java.util.ArrayList;  
 import java.util.Iterator;  
 import java.util.List;  
 import org.apache.poi.hssf.usermodel.HSSFCell;  
 import org.apache.poi.hssf.usermodel.HSSFRow;  
 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.Row;  
 public class ExcelTransaction {  
      static public List<List<HSSFCell>> readExcelFile(String path) throws IOException{  
           List<List<HSSFCell>> sheetData = new ArrayList<List<HSSFCell>>();  
           FileInputStream fis = new FileInputStream(path);  
           try {  
                HSSFWorkbook wb = new HSSFWorkbook(fis);  
                HSSFSheet sheet = wb.getSheetAt(0);  
                //Excell dosyasında satırlar için iterator oluşturuluyor.  
                Iterator<Row> rows = sheet.rowIterator();  
                //Satırlar geziliyor.  
                while (rows.hasNext()) {  
                     HSSFRow row = (HSSFRow)rows.next();  
                     //Satırda bulunan hücreler icin iterator olusturuluyor.  
                     Iterator<Cell> cells = row.cellIterator();  
                     List<HSSFCell> cellList = new ArrayList<HSSFCell>();  
                     //Hücreler geziliyor.  
                     while (cells.hasNext()) {  
                          HSSFCell cell = (HSSFCell) cells.next();  
                          cellList.add(cell);  
                     }  
                     sheetData.add(cellList);  
                }  
                return sheetData;  
           } catch (IOException e) {  
                e.printStackTrace();  
           }finally  
           {  
                if(fis != null)  
                     fis.close();  
           }  
           return null;  
      }  
      public static void main(String[] args) throws IOException {  
           List<List<HSSFCell>> list = readExcelFile("D:\\Users\\emre.sevinc\\Desktop\\ornek.xls");  
           for (List<HSSFCell> object : list) {  
                System.out.println(object);  
           }  
      }  
 }  

Projelerinizde bir excel dosyasında bulunan verileri okuma veya işleme ihtiyacı duyabilirsiniz. Java dilinde bu soruna çözüm olarak Apache firmasının geliştirmiş olduğu apache.poi kütüphanesi size yardımcı olabilir. Yukarıdaki kod örneğinde bir excel dosyasının nasıl okunabileceğini örnekledim. Kodu inceleyebilirsiniz.

Hiç yorum yok:

Yorum Gönder