Import file XLS ke Swing JTable

Manipulasi file XLS dalam program Java dapat menggunakan library apache POI, berikut skrip baca file XLS untuk ditampilkan kedalam JTable

package esindo.net.payroll;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.DefaultTableModel;
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;

/**
 *
 * @author rojulman
 */
public class SwingUtil {

    public static DefaultTableModel getTableModel(File file) {
        int index = -1;
        HSSFWorkbook workbook = null;
        DefaultTableModel model = null;
        try {
            try {
                FileInputStream inputStream = new FileInputStream(file);
                workbook = new HSSFWorkbook(inputStream);
            } catch (IOException ex) {
                ex.printStackTrace();
              //  Logger.getLogger(PegawaiService.class.getName()).log(Level.SEVERE, null, ex);
            }

            int sheet_index = 0;// sheet pertama
            HSSFSheet sheet = workbook.getSheetAt(sheet_index);
            HSSFRow row = sheet.getRow(0);

            Vector headers = new Vector();
            Vector data = new Vector();

            headers.clear();
            for (int i = 0; i < row.getLastCellNum(); i++) {
                HSSFCell cell1 = row.getCell(i);
                headers.add(cell1.toString());
            }

            data.clear();
            for (int j = 1; j < sheet.getLastRowNum() + 1; j++) {
                Vector d = new Vector();
                row = sheet.getRow(j);
                int noofrows = row.getLastCellNum();
                for (int i = 0; i < noofrows; i++) {    //To handle empty excel cells
                    HSSFCell cell = row.getCell(i,
                            org.apache.poi.ss.usermodel.Row.CREATE_NULL_AS_BLANK);
                    d.add(cell.toString());
                }
                d.add("\n");
                data.add(d);
            }
            model = new DefaultTableModel(data, headers);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

}

Penggunaan pada JFrame

      File file = new File("D:\data_pegawai.xls");
     // instan JTable : tblPegawai
      tblPegawai.setModel(SwingUtil.getTableModel(file));

Post a Response