【poi第二节】poi读取excel.java读取excel

x33g5p2x  于2021-12-28 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(442)

poi读取excel.java读取excel

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.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileInputStream;
import java.io.InputStream;

/**
 * @ClassName 类名:ExcelDemo2
 * @Author作者: hzh
 * @Date时间:2018/12/4 9:48
 * excel读取
 **/
public class ExcelDemo2 {

    public static void main(String[] args) throws Exception{
        InputStream inputStream = new FileInputStream("D:\\file\\工作薄.xls");
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
        HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
        HSSFSheet hssfSheet = wb.getSheetAt(0); //获取第一个sheet
        if(hssfSheet == null){
            return;
        }
        //遍历行row
        for(int rowNum=0;rowNum<=hssfSheet.getLastRowNum();rowNum++){
            HSSFRow hssfRow = hssfSheet.getRow(rowNum);
            if(hssfRow == null){
                continue;
            }
            //遍历列cell
            for(int cellNum=0;cellNum<=hssfRow.getLastCellNum();cellNum++){
                HSSFCell hssfCell = hssfRow.getCell(cellNum);
                if(hssfCell == null){
                    continue;
                }
                System.out.print(" "+getValue(hssfCell));
            }
            System.out.println();
        }

    }

    /**
     * 值类型转化
     * @param hssfCell
     * @return
     */
    private static String getValue(HSSFCell hssfCell){
        if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_BOOLEAN){
            return String.valueOf(hssfCell.getBooleanCellValue());
        }else if(hssfCell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC){
            return String.valueOf(hssfCell.getNumericCellValue());
        }else {
            return hssfCell.getStringCellValue();
        }
    }

}

相关文章