美文网首页
POI处理导入Excel

POI处理导入Excel

作者: 十二找十三 | 来源:发表于2022-06-02 09:30 被阅读0次
<!-- poi dependency-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.15</version>
</dependency>
    @RequestMapping("aaa")
    public String aaa(@Param("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        System.out.println(fileName.substring(fileName.lastIndexOf(".") + 1)); // 文件后缀
        System.out.println("fileName=>" + fileName); //文件名称

        try {
            System.out.println(POIUtil.parseExcel(file.getInputStream(), fileName.substring(fileName.lastIndexOf(".") + 1)));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "OK";
    }
package com.ccbckj.common.controller.Export;

import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;


public class POIUtil {

//    public static void main(String[] args) {
//        try {
//            FileInputStream fileInputStream = new FileInputStream("E:\\ccbckj\\123\\新业态企业导入模版.xlsx");
//            List<List<Map<String, String>>> data = parseExcel(fileInputStream, "xlsx");
//            System.out.println(data.size());
//            System.out.println(data);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
//    }

    // 主要用于导入Excel解析
    public static List<List<Map<String, String>>> parseExcel(InputStream inputStream, String suffix) {
        Workbook workbook = null;//Excel对象

        if ("xls".equals(suffix)) {// 2003版的解析方式
            try {
                workbook = new HSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else if ("xlsx".equals(suffix)) {// 2007版本Excel
            try {
                workbook = new XSSFWorkbook(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            return null;
        }

        int allSheets = workbook.getNumberOfSheets(); // 获取Sheet总数

        List<List<Map<String, String>>> result = new ArrayList<>(allSheets);

        for (int sheetI = 0; sheetI < allSheets; sheetI++) {
            Sheet sheet = workbook.getSheetAt(sheetI);
            if (sheet == null) {
                return null;
            }

            //获取表格中最后一行的行号
            int lastRowNum = sheet.getLastRowNum();

            List<Map<String, String>> sheetItem = new ArrayList<>();

            //定义行变量和单元格变量
            Row row = null;
            Cell cell = null;
            //循环读取
            for (int rowNum = 0; rowNum <= lastRowNum; rowNum++) {
                row = sheet.getRow(rowNum);
                // 获取当前行的第一列和最后一列的标记
                if (null != row) {
                    short firstCellNum = row.getFirstCellNum();
                    short lastCellNum = row.getLastCellNum();
                    if (lastCellNum != 0) {
                        int containerSize = (int) (lastCellNum / 0.75 + 1);
                        Map<String, String> rowData = new HashMap<>(containerSize);

                        for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                            cell = row.getCell(cellNum);
                            // 判断单元格是否有数据
                            if (cell == null) {
                                // 我的业务是暂无数据不处理
                            } else {
                                rowData.put(sheetI + "_" + rowNum + "_" + cellNum, parseCell(cell)); // key 为 sheet的索引 + 行索引 + 列索引
                            }
                        }
                        sheetItem.add(rowData);
                    }
                }
            }

            result.add(sheetItem);
        }
        return result;
    }


    // 解析单元格数据  -> 返回字符串
    private synchronized static String parseCell(Cell cell) {
        String cellStr = null;
        switch (cell.getCellTypeEnum()) {// 判断单元格的类型 不同版本API可能过时
            case STRING: //字符串类型单元格
                cellStr = cell.getRichStringCellValue().toString();
                break;
            case BLANK: //空数据
                cellStr = "";
                break;
            case NUMERIC: // 数字类型 包含日期、时间、数字
                //判断日期【年月日2016-12-20  | 时分10:20】类型
                if (HSSFDateUtil.isCellDateFormatted(cell)) { //判断具体类型,是日期还是时间
                    SimpleDateFormat sdf = null;
                    if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
                        //时间
                        sdf = new SimpleDateFormat("HH:mm");
                    } else {
                        //日期
                        sdf = new SimpleDateFormat("yyyy-MM-dd");
                    }
                    Date temp = cell.getDateCellValue();
                    cellStr = sdf.format(temp);
                } else { //数字
                    double temp = cell.getNumericCellValue();
                    DecimalFormat format = new DecimalFormat();//数字格式化工具
                    //查看单元格中的具体样式类型
                    String formatStr = cell.getCellStyle().getDataFormatString();
                    if (formatStr.equals("General")) {
                        /**
                         * 格式化正则
                         * 保留整数 #
                         * 保留一位小数 #.#
                         * 保留两位小数#.##
                         */
                        format.applyPattern("#.##");
                    }
                    cellStr = format.format(temp);
                }
                break;
            default:
                cellStr = "";

        }
        return cellStr;
    }
}

相关文章

网友评论

      本文标题:POI处理导入Excel

      本文链接:https://www.haomeiwen.com/subject/iqxqmrtx.html