【excel】读取excel 中内容

1. 根据上传 excel  文件读取

所需jar 包:

    compile group: 'org.apache.poi', name: 'poi', version: '3.13'//word excel 解析
    compile group: 'org.apache.poi', name: 'poi-ooxml', version: '3.13'//word excel 解析
    compile group: 'org.apache.poi', name: 'poi-scratchpad', version: '3.13'//word excel 解析


示例代码

/**
     * 从上传文件中获取预览数据
     */
    public List<List<String>> readFromUploadExcel(MultipartFile file, boolean hasTitle) {
        InputStream inputStream;
        List<List<String>> lists = new ArrayList<>();
        try {
            inputStream = file.getInputStream();
            lists = this.readExcel(inputStream, hasTitle, 20);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lists;
    }

private List<List<String>> readExcel(InputStream inputStream, boolean hasTitle, int maxLine) {
        List<List<String>> lists = new ArrayList<>();

        try {
            Workbook workbook = WorkbookFactory.create(inputStream);
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            Sheet sheet = workbook.getSheetAt(0);

            int rows = sheet.getLastRowNum();   //总行数 ,第一行标题未计入
            Row row = sheet.getRow(0);
            int cols = row.getLastCellNum(); //总列数
            int startRow = hasTitle ? 1 : 0;
            int readLines = rows;
            if (maxLine > 0 && maxLine < rows) {
                readLines = maxLine;
            }
            for (int i = startRow; i <= readLines; i++) { //遍历每一行 0 为标题
                row = sheet.getRow(i);
                List<String> list = new ArrayList<>();
                for (int j = 1; j <= cols - 1; j++) { //遍历每一列
                    Cell cell = row.getCell(j);
                    list.add(getCellValue(cell, evaluator));
                }
                lists.add(list);
            }
        } catch (IOException | InvalidFormatException e) {
            e.printStackTrace();
        }
        return lists;
    }

//考虑到 数据类型以及用到的函数解析
private String getCellValue(Cell cell, FormulaEvaluator evaluator) {
        if (cell == null) {
            return "";
        }
        String cellValue = "";
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_STRING:
                cellValue=cell.getStringCellValue();
                break;
            case Cell.CELL_TYPE_NUMERIC:
                cellValue=String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA:
                cellValue=getCellValue(evaluator.evaluate(cell));
                break;
            default:
                break;
        }

        return cellValue;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值