Java相关

Java poi 处理 Excel 文件

2021-11-10  本文已影响0人  思念_似水流年

一、引入依赖

<!-- POI 支持,适用于高版本,即 xlsx 为后缀的 Excel 表格 -->
  <dependency>
        <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>4.1.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>4.1.2</version>
        </dependency>

二、编写工具类

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * add by sn
 */
@Slf4j
public class AnalysisExcelUtil {

    public static Workbook getWorkBook(MultipartFile file){
        // get fileName
        String fileName = file.getOriginalFilename();
        // create workbook
        Workbook workbook = null;
        try {
            InputStream is = file.getInputStream();
            // 根据文件名后缀不同获得不同的 workbook 实现类对象
            if (fileName.endsWith("xls")) {
                // 2003
                workbook = new HSSFWorkbook(is);
            } else if (fileName.endsWith("xlsx")) {
                // 2007 or higher
                workbook = new XSSFWorkbook(is);
            }
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return workbook;
    }

    public static boolean rowIsEmpty(Row row) {
        if (null == row) {
            return true;
        }
        for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
            Cell cell = row.getCell(c);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }

    public static String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return cellValue;
        }
        switch (cell.getCellType()) {
            case NUMERIC:
                // 数字
                cellValue = stringDateProcess(cell);
                break;
            case STRING:
                // 字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case BOOLEAN:
                // boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case FORMULA:
                // 公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case BLANK:
                // 空值
                cellValue = "";
                break;
            case ERROR:
                // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
        return cellValue;
    }

    public static String stringDateProcess(Cell cell) {
        String result = new String();
        if (DateUtil.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 HH:mm:ss");
            }
            Date date = cell.getDateCellValue();
            result = sdf.format(date);
        } else if (cell.getCellStyle().getDataFormat() == 58) {
            // 处理自定义日期:m月d日(通过判断单元格的格式id解决,id的值是58)
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            double value = cell.getNumericCellValue();
            Date date = DateUtil.getJavaDate(value);
            result = sdf.format(date);
        } else {
            double value = cell.getNumericCellValue();
            CellStyle style = cell.getCellStyle();
            DecimalFormat format = new DecimalFormat();
            String temp = style.getDataFormatString();
            // 单元格设置成常规
            if (temp.equals("General")) {
                format.applyPattern("#");
            }
            result = format.format(value);
        }

        return result;
    }

    public static boolean checkFile(MultipartFile file) {
        if (null == file) {
            log.error("文件不存在!");
            return false;
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 判断文件是否是 excel 文件
        if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) {
            log.error(fileName + "不是 excel 文件!");
            return false;
        }
        return true;
    }
}

三、使用工具方法处理上传的 excel 文件

/**
     * 从上传的 xlsx 中获取到对应列的数据
     * 第一列是sessionId,第二列是时间
     * @param startRow 指定开始的行
     * @param file 上传的文件
     * @return
     */
    public Response<Map<String, String>> getExcelData(MultipartFile file, int startRow) throws IOException {
        Map<String, String> resultMap = new HashMap<>();
        if (!AnalysisExcelUtil.checkFile(file)) {
            log.error("上传的excel 文件格式有问题");
            return Response.error("上传的excel 文件格式有问题");
        }
        // 获取 workbook 工作簿对象
        Workbook workbook = AnalysisExcelUtil.getWorkBook(file);
        if (workbook != null) {
            // get first sheet
            Sheet sheet = workbook.getSheetAt(0);
            if (sheet == null) {
                return Response.error("第一个Sheet为空");
            }

            // 获取当前 sheet 的开始行
            int firstRowNum = sheet.getFirstRowNum();
            // 获取当前 sheet 的结束行
            int lastRowNum = sheet.getLastRowNum();
            // 循环除了 startRow 的所有行,如果要循环除第一行外的就 firstRowNum + 1
            for (int rowNum = firstRowNum + startRow; rowNum <= lastRowNum; rowNum++) {
                // 获取当前行
                Row row = sheet.getRow(rowNum);
                if (AnalysisExcelUtil.rowIsEmpty(row)) {
                    break;
                }
                // 获取当前行的开始列
                int firstCellNum = row.getFirstCellNum();
                // 获取当前行的列数
                int lastCellNum = row.getLastCellNum();
                Map<String, String> cellMap = new HashMap<>(2);

                Cell cell0 = row.getCell(0);
                Cell cell1 = row.getCell(1);
                resultMap.put(AnalysisExcelUtil.getCellValue(cell0), AnalysisExcelUtil.getCellValue(cell1));
            }
            workbook.close();
        }
        return Response.success(resultMap);
    }
上一篇下一篇

猜你喜欢

热点阅读