อ่าน xlsx ด้วย java


CODE อ่าน xlsx ด้วย java

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 *
 * @author mossila
 */
public class XlsxHelper {

    public static ArrayList<ArrayList<String>> readSheet(String filename, int startrecord) throws Exception {

        FileInputStream fis = null;
        ArrayList<ArrayList<String>> table = new ArrayList<ArrayList<String>>();
        try {
            fis = new FileInputStream(filename);

            XSSFWorkbook workbook = new XSSFWorkbook(fis);
            XSSFSheet sheet = workbook.getSheetAt(0);
            Iterator rows = sheet.rowIterator();

            int rowscount = 0;

            while (rows.hasNext()) {
                ArrayList<String> record = new ArrayList<String>();
                rowscount++;
                XSSFRow row = ((XSSFRow) rows.next());
                Iterator cells = row.cellIterator();
                while (cells.hasNext()) {
                    XSSFCell cell = (XSSFCell) cells.next();
                    Double numeric = new Double(0);
                    String othervalue = new String();
                    if (XSSFCell.CELL_TYPE_NUMERIC == cell.getCellType()) {
                        numeric = cell.getNumericCellValue();
                        if (rowscount > startrecord) {
                            record.add("" + numeric);
                        }
                    } else {
                        othervalue = cell.getStringCellValue();
                        if (rowscount > startrecord) {
                            record.add(othervalue);
                        }
                    }
                }
                if (rowscount > startrecord) {
                    table.add(record);
                }

            }
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            if (fis != null) {
                fis.close();
            }
        }
        return table;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s