使用 POI 读取 Excel 表格数据

参考资料: http://blog.csdn.net/slience_perseverance/article/details/8228157

引入 gradle 依赖:

compile 'org.apache.poi:poi:3.14-beta1'
public static void main(String[] args) {
    try {
        // 读取文件
        InputStream is = new FileInputStream("002.xls");
        // 将文件流解析成 POI 文档
        POIFSFileSystem fs = new POIFSFileSystem(is);
        // 再将 POI 文档解析成 Excel 工作簿
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFRow row = null;
        HSSFCell cell = null;
        // 得到第 1 个工作簿
        HSSFSheet sheet = wb.getSheetAt(0);
        // 得到这一行一共有多少列
        int totalColumns = sheet.getRow(0).getPhysicalNumberOfCells();
        // 得到最后一行的坐标
        Integer lastRowNum = sheet.getLastRowNum();
        System.out.println("lastRowNum => " + lastRowNum);

        List<CorpusWord> corpusBeanList = new ArrayList<>();
        CorpusWord corpusBean = null;
        String cellValue = null;

        // 从第 2 行开始读
        for(int i=1;i<=lastRowNum;i++){
            row = sheet.getRow(i);
            corpusBean = new CorpusWord();
            for(int j=0;j<totalColumns;j++){
                cell = row.getCell(j);
                if(cell!=null){
                    cellValue = cell.getStringCellValue();
                }else {
                    cellValue = "【没有数据】";
                }
                if(j==0){
                    corpusBean.setKey(cellValue);
                }
                if(j==1){
                    corpusBean.setAnnotation(cellValue);
                }
                if(j==2){
                    corpusBean.setType(cellValue);
                    corpusBean.setSource("自建");
                    corpusBean.setPre("");
                    corpusBean.setSuf("");
                }
            }
            corpusBeanList.add(corpusBean);
        }
        for(CorpusWord cb:corpusBeanList){
            System.out.println(cb);
        }
        System.out.println("数据条数:" + corpusBeanList.size());



    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值