java 從EXCEL匯入到系統

FH-Admin 發表於 2022-01-11
Java Excel
package org.fh.util;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
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.fh.entity.PageData;

/**
 * 說明:從EXCEL匯入到系統
 * 作者:FH Admin
 * from:fhadmin.cn
 */
public class ObjectExcelRead {

    /**
     * @param filepath //檔案路徑
     * @param filename //檔名
     * @param startrow //開始行號
     * @param startcol //開始列號
     * @param sheetnum //sheet
     * @return list
     */
    public static List<Object> readExcel(String filepath, String filename, int startrow, int startcol, int sheetnum) {
        List<Object> varList = new ArrayList<Object>();

        try {
            File target = new File(filepath, filename);
            FileInputStream fi = new FileInputStream(target);
            HSSFWorkbook wb = new HSSFWorkbook(fi);
            HSSFSheet sheet = wb.getSheetAt(sheetnum);                     //sheet 從0開始
            int rowNum = sheet.getLastRowNum() + 1;                     //取得最後一行的行號

            for (int i = startrow; i < rowNum; i++) {                    //行迴圈開始

                PageData varpd = new PageData();
                HSSFRow row = sheet.getRow(i);                             //行
                int cellNum = row.getLastCellNum();                     //每行的最後一個單元格位置

                for (int j = startcol; j < cellNum; j++) {                //列迴圈開始

                    HSSFCell cell = row.getCell(Short.parseShort(j + ""));
                    varpd.put("var"+j, cell.toString());

                }
                varList.add(varpd);
            }

        } catch (Exception e) {
            System.out.println(e);
        }

        return varList;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結