读取excel表格数据

image.png

pom.xml中依赖

        
        
            org.apache.poi
            poi
            3.17
        

        
            org.apache.poi
            poi-ooxml
            3.17
        

其中columns是表格的列

    /**
     * 读取excel表格数据
     */
    public List> importExcel(HttpServletRequest request) throws IOException, BusinessException {

        if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            Set> set = multipartRequest.getFileMap().entrySet();
            for (Map.Entry multipartFileEntry : set) {
                MultipartFile multipartFile = multipartFileEntry.getValue();
                String fileName = multipartFile.getOriginalFilename();
                InputStream inputStream = null;
                Workbook workBook = null;
                FileInputStream fis = null;

                fis = (FileInputStream) multipartFile.getInputStream();

                if (fileName.endsWith("xls")) {
                    workBook = new HSSFWorkbook(fis);
                } else if (fileName.endsWith("xlsx")) {
                    workBook = new XSSFWorkbook(fis);
                } else {

                }

                Sheet sheet = null;
                Row row = null;
                List> list = new ArrayList<>();
                String cellData = null;
                String columns[] = {"a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "a10", "a11", "a12", "a13"};

                if (workBook != null) {
                    //获取第一个sheet
                    sheet = workBook.getSheetAt(0);
                    //获取最大行数
                    int rownum = sheet.getPhysicalNumberOfRows();
                    //获取第一行
                    row = sheet.getRow(0);
                    //获取最大列数
                    int colnum = row.getPhysicalNumberOfCells();
                    for (int i = 1; i < rownum; i++) {
                        Map map = new LinkedHashMap();
                        row = sheet.getRow(i);
                        if (row != null) {
                            for (int j = 0; j < 13; j++) {
                                cellData = ExcelUtil.getStringCellValue(row.getCell(j));
                                map.put(columns[j], cellData);
                            }
                        } else {
                            break;
                        }
                        list.add(map);
                    }
                }

                return list;
            }
            throw new BusinessException("没有找到文件");
        } else {
            throw new BusinessException("没有找到文件");
        }
    }

你可能感兴趣的:(读取excel表格数据)