Excel导入解析

一、导入Jar包、引入MAVEN依赖

1.涉及的jar包: poi、poi-ooxml、poi-ooxml-schemas、xmlbeans、dom4j
2.maven库: https://mvnrepository.com/
3.依赖引入/Jar包导入

二、文件格式校验

1)判断Excel文件是否存在

/**
     * 检查文件是否为excel或者为空
     *
     * @param filePath 文件路径
     * @return boolean
     */
    public boolean validateExcel(String filePath) {
        //检查文件格式
        if (!(ReadExcel.isExcel2003(filePath) || ReadExcel.isExcel2007(filePath))) {
            errorInfo = "不是excel格式";
            return false;
        }
        //检查文件是否存在
        File file = new File(filePath);
        if (!file.exists()) {
            errorInfo = "文件不存在";
            return false;
        }
        return true;
    }

2)判断Excel文件类型

/**
     * 判断是否xls格式
     *
     * @param filePath
     * @return boolean
     */
    public static boolean isExcel2003(String filePath) {
        return filePath.matches("^.+\\.(?i)(xls)$");
    }

    /**
     * 判断是否xlsx格式
     *
     * @param filePath 文件路径
     * @return boolean
     */
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

三、Excel解析

1)Excel文件流解析

/**
     * 文件及类型解析
     *
     * @param filePath 文件路径
     * @return List>
     */
    public List> read(String filePath) {
        List> dataList = new ArrayList<>();
        InputStream is = null;

        if (!validateExcel(filePath)) {
            return null;
        } else {
            try {
                //判断文件类型
                boolean isExcel2003 = true;
                if (ReadExcel.isExcel2007(filePath)) {
                    isExcel2003 = false;
                }

                //调用读取方法
                File file = new File(filePath);
                is = new FileInputStream(file);
                dataList = readStream(is, isExcel2003);
                is.close();
            } catch (Exception e) {
                errorInfo = "文件上传失败,请重新上传";
            }
            return dataList;
        }
    }
/**
     * 文件及类型解析
     *
     * @param inputStream 文件输入流
     * @param isExcel2003 是否是xls
     * @return List>
     * @throws Exception 抛出
     */
    public List> readStream(InputStream inputStream, boolean isExcel2003) throws Exception {
        List> dataList = null;

        Workbook wb = null;
        if (isExcel2003) {
            //HSSF是POI工程对Excel 97(-2007)文件操作
            wb = new HSSFWorkbook(inputStream);
        } else {
            //XSSF是POI工程对Excel 2007 OOXML (.xlsx)文件操作
            wb = new XSSFWorkbook(inputStream);
        }

        dataList = readWork(wb);
        return dataList;
    }

2)Excel解析主方法

/**
     * Excel解析主方法
     *
     * @param wb excel的对象
     * @return List>
     */
    public List> readWork(Workbook wb) {
        List> dataList = new ArrayList<>();
        //用于记录不匹配列
        StringBuffer stringBuffer = new StringBuffer();
        //得到第一个shell
        Sheet sheet = wb.getSheetAt(0);
        this.totalRows = sheet.getPhysicalNumberOfRows();

        if (this.totalRows >= 2 && sheet.getRow(1) != null) {
            this.totalCells = sheet.getRow(0).getPhysicalNumberOfCells();
            //校验模板是否正确
            if (totalCells != title.length) {
                errorInfo = "Excel模板列数与导入Excel列数不匹配!!!";
            } else {
                for (int i = 0; i < title.length; i++) {
                    //第一行列取值
                    String topTitle = String.valueOf(sheet.getRow(0).getCell(i));
                    if (!title[i].equals(topTitle)) {
                        stringBuffer.append("《");
                        stringBuffer.append(topTitle);
                        stringBuffer.append("》");
                        stringBuffer.append(",");
                    }
                }
                if (stringBuffer.length() > 0) {
                    stringBuffer.deleteCharAt(stringBuffer.length() - 1);
                    errorInfo = "Excel模板不存在" + stringBuffer + "列标题!!!";
                }
            }
            //解析Excel
            if (errorInfo == null) {
                //循环excel的行
                for (int r = 1; r < this.getTotalRows(); r++) {
                    Row row = sheet.getRow(r);
                    if (row == null) {
                        continue;
                    }
                    //rowList集合对应每一行数据
                    List rowList = new ArrayList<>();
                    //循环excel的列
                    for (int c = 0; c < this.getTotalCells(); c++) {
                        Cell cell = row.getCell(c);
                        String cellValue = "";
                        if (cell != null) {
                            //判断数据类型
                            switch (cell.getCellType()) {
                                //数字
                                case HSSFCell.CELL_TYPE_NUMERIC:
                                    cellValue = cell.getNumericCellValue() + "";
                                    break;
                                //字符串
                                case HSSFCell.CELL_TYPE_STRING:
                                    cellValue = cell.getStringCellValue();
                                    break;
                                //布尔
                                case HSSFCell.CELL_TYPE_BOOLEAN:
                                    cellValue = cell.getBooleanCellValue() + "";
                                    break;
                                //公式
                                case HSSFCell.CELL_TYPE_FORMULA:
                                    cellValue = cell.getCellFormula() + "";
                                    break;
                                //空
                                case HSSFCell.CELL_TYPE_BLANK:
                                    cellValue = "";
                                    break;
                                //故障
                                case HSSFCell.CELL_TYPE_ERROR:
                                    cellValue = "非法字符";
                                    break;
                                default:
                                    cellValue = "未知类型";
                                    break;
                            }
                        }
                        rowList.add(cellValue);
                    }
                    dataList.add(rowList);
                }
                return dataList;
            } else {
                return null;
            }
        } else {
            errorInfo = "请核查Excel是否存在数据!!!";
            return null;
        }
    }

四、方法调用

package com.work.excel;

import org.apache.poi.hssf.usermodel.HSSFCell;
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.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class ReadExcel {
/**
     * 总行数
     */
    private int totalRows = 0;
    /**
     * 总列数
     */
    private int totalCells = 0;
    /**
     * 错误信息
     */
    private String errorInfo = null;
    /**
     * 模板标题列
     */
    String[] title = {"姓名", "年龄", "学历", "手机号", "邮箱", "地址"};

    private ReadExcel() {

    }

    public int getTotalRows() {
        return totalRows;
    }

    public int getTotalCells() {
        return totalCells;
    }

    public String getErrorInfo() {
        return errorInfo;
    }
/**
     * 方法调用
     */
    public void mainMothd(){
        ReadExcel t = new ReadExcel();
        //地址范例
        String filePath = "C:\\Users\\Administrator\\Desktop\\模板.xlsx";
        List> list = t.read(filePath);
        if (list != null) {
            System.out.println("********************正在解析***********************");
            for (int i = 0; i < list.size(); i++) {
                System.out.print("第" + (i + 1) + "行:");
                List cellList = list.get(i);
                for (String s : cellList) {
                    System.out.print("   " + s);
                }
                System.out.println();
            }
            System.out.println("********************解析完成***********************");
        } else {
            System.out.println(t.getErrorInfo());
        }
    }

    /**
     * main方法
     * @param args
     */
    public static void main(String[] args) {
        ReadExcel t = new ReadExcel();
        t.mainMothd();
    }
}

你可能感兴趣的:(Excel导入解析)