zoukankan      html  css  js  c++  java
  • POI读取Excel数据

    POI读取Excel表格数据

    所需相关jar下载: 

    commons-collections4-4.4.jar

    commons-compress-1.19.jar

    poi-4.1.1.jar

    poi-ooxml-4.1.1.jar

    poi-ooxml-schemas-4.1.1.jar

    class Import jar:

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.text.DecimalFormat;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.ss.usermodel.Cell;
    import org.apache.poi.ss.usermodel.CellType;
    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;

    根据Excel的地址读取Excel表格数据

    /**
         * @Title:getDataFromExcel
         * @author:马家立
         * @date:2019年11月19日 上午10:02:22
         * @Description:TODO 根据Excel的地址读取Excel表格数据
         * @param filePathExcel的绝对路径
         * @return Map<String,Object> {end:ok或者error;msg:错误信息原因;counts:读取条数}
         * @throws IOException
         */
        public static Map<String, Object> getDataFromExcel(String filePath) throws IOException {
            // 声明结果map
            Map<String, Object> resultMap = new HashMap<String, Object>();
            // 判断是否为excel类型文件
            if (!filePath.endsWith(".xls") && !filePath.endsWith(".xlsx")) {
                System.out.println("文件不是excel类型");
                resultMap.put("end", "error");
                resultMap.put("msg", "文件不是excel类型");
                return resultMap;
            }
            // 声明文本输入流
            FileInputStream fis = null;
            // 声明一个新的工作簿
            Workbook wookbook = null;
            // 声明一个新的工作表
            Sheet sheet = null;
            try {
                // 获取一个绝对地址的流
                fis = new FileInputStream(filePath);
                // 2003版本的excel,用.xls结尾, 2007版本以.xlsx
                if (filePath.endsWith(".xls")) {
                    wookbook = new HSSFWorkbook(fis);// 得到工作簿
                } else {
                    // XSSFWorkbook
                    wookbook = new XSSFWorkbook(fis);// 得到工作簿
                }
                // 得到第一个工作表
                sheet = wookbook.getSheetAt(0);
                // 得到第二个工作表
                // sheet = wookbook.getSheetAt(1);
                // 得到第三个工作表
                // sheet = wookbook.getSheetAt(2);
                // 封装处理Excel工作子表的数据
                resultMap = packageDataBySheet(sheet);
            } finally {
                if (!QwyUtil.isNullAndEmpty(wookbook)) {
                    wookbook.close();
                }
            }
            return resultMap;
        }

    封装处理Excel工作子表的数据

    /**
         * @Title:packageDataBySheet
         * @author:马家立
         * @date:2019年11月19日 上午9:55:26
         * @Description:TODO 封装处理Excel工作子表的数据
         * @param sheetExcel工作簿中的子表
         * @return Map<String,Object> {end:ok或者error;msg:错误信息原因;counts:读取条数}
         */
        public static Map<String, Object> packageDataBySheet(Sheet sheet) {
            // 返回结果map
            Map<String, Object> resultMap = new HashMap<String, Object>();
            try {
                resultMap.put("end", "ok");
                // 获得表头
                Row rowHead = sheet.getRow(0);
                // 获取Excel的所有行数量
                int rows = sheet.getLastRowNum();
                // 获取Excel的所有列数量
                int lines = rowHead.getPhysicalNumberOfCells();
                if (0 == rows) {
                    System.out.println("Excel文件内没有数据!");
                    resultMap.put("end", "error");
                    resultMap.put("msg", "Excel文件内没有数据!");
                    return resultMap;
                }
                // 读取条数
                int counts = 0;
                // 是否跳过读取下一行
                boolean isNext = false;
                // 外圈循环读取所有行:获得所有行的数据
                for (int i = 0; i <= rows; i++) {
                    // 是否跳过读取下一行:每次初始化为false
                    isNext = false;
                    counts++;
                    // 获得第i行对象
                    Row row = sheet.getRow(i);
                    // 获取单元格为空则直接下一行
                    if (isNullAndEmpty(row)) {
                        continue;
                    }
                    List<String> list = new ArrayList<>();
                    // 内圈循环读取所有列:遍历每一行的的数据,lineNum:列数
                    for (int j = 0; j < lines; j++) {
                        // 获取该单元格相应的类型的值
                        String str = getRightTypeCell(row.getCell(j), i, j);
                        // 如果第一列为空则直接读取下一行
                        if (isNullAndEmpty(str) && (0 == j)) {
                            isNext = true;
                            break;
                        }
                        list.add(str);
                    }
                    // 是否跳过读取下一行
                    if (isNext) {
                        continue;
                    }
                    String str1 = list.get(0); // 参数1
                    // String str2 = list.get(1); // 参数2
                    // String str3 = list.get(2); // 参数3
                    // and so on...
                    if (i == 0) {
                        if ("str1".endsWith(str1)) {
                            System.out.println("读取的排课Excel数据格式正确");
                        } else {
                            resultMap.put("end", "error");
                            resultMap.put("msg", "读取的排课Excel数据格式错误!");
                            System.err.println("读取的排课Excel数据格式错误");
                            break;
                        }
                    } else {
                        /**
                         * 处理数据
                         */
                    }
    
                }
                resultMap.put("counts", counts + "");
            } catch (Exception e) {
                e.printStackTrace();
                resultMap.put("end", "error");
                resultMap.put("msg", "OperationExcel的packageDataBySheet方法异常!");
            }
            return resultMap;
        }

    返回该单元格相应的类型的值

    /**
         * @Title:getRightTypeCell
         * @author:马家立
         * @date:2020年6月26日 上午11:55:55
         * @Description:TODO 返回该单元格相应的类型的值
         * @param cell--一个单元格的对象
         * @param rowNum--行数
         * @param lineNum--列数
         * @return String
         * @throws Exception
         */
        public static String getRightTypeCell(Cell cell, int rowNum, int lineNum) throws Exception {
            // 单元格内容
            String result = "";
            System.out.println("rowNum:" + rowNum + "	lineNum:" + lineNum);
            // 如果单元格为空或者单元格里面的数据为空则返回
            if ((cell == null) || cell.equals(null) || (CellType.BLANK == cell.getCellType())) {
                result = "";
            } else {
                // 判断数据类型
                switch (cell.getCellType()) {
                    case BLANK:
                        result = cell.getStringCellValue();
                        break;
                    case BOOLEAN:
                        result = String.valueOf(cell.getBooleanCellValue());
                        break;
                    case ERROR:
                        result = String.valueOf(cell.getErrorCellValue());
                        break;
                    case FORMULA:
                        result = cell.getCellFormula();
                        break;
                    case NUMERIC:
                        result = String.valueOf(cell.getNumericCellValue());
                        /**
                         * --#与0的区别{#:没有则为空;0:没有则补0}
                         */
                        // 没有则自动补.00--100则为100.00;100.00则为100.00;1.05则为1.05;1.5则为1.50
                        // result = new DecimalFormat("0.00").format(cell.getNumericCellValue());
                        // 100则为100;100.00则为100;1.05则为1.05;1.5则为1.5
                        result = new DecimalFormat("0.##").format(cell.getNumericCellValue());
                        break;
                    case STRING:
                        result = cell.getRichStringCellValue().getString();
                        break;
                    default:
                        result = cell.getStringCellValue();
                        break;
                }
            }
            return result;
        }

     校验对象是否为空

     /**
         * @Title:isNullAndEmpty
         * @author:马家立
         * @date:2019年11月19日 上午10:23:49
         * @Description:TODO 校验对象是否为空
         * @param obj校验对象
         * @return boolean
         */
        public static boolean isNullAndEmpty(Object obj) {
            if ((null != obj) && !"".equals(obj.toString()) && !"null".equals(obj)) {
                return false;
            } else {
                return true;
            }
        }

    main方法测试

    public static void main(String[] args) {
            try {
                // 读取文件地址
                String file_path = "D:\123.xlsx";
                String end;
                // 传路径是为了方法灵活
                Map<String, Object> map = getDataFromExcel(file_path);
                end = map.get("end") + "";
                System.out.println("封装处理结果:" + end);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
  • 相关阅读:
    POJ 2456 Aggressive cows
    POJ 1064 Cable master
    POJ 3723 Conscription
    左偏树
    tarjan模板
    [bzoj5017][Snoi2017]炸弹 tarjan缩点+线段树优化建图+拓扑
    [BZOJ4520][Cqoi2016]K远点对 kd-tree 优先队列
    [bzoj3218]a + b Problem 网络流+主席树优化建图
    #6034. 「雅礼集训 2017 Day2」线段游戏 李超树
    【UOJ UNR #1】火车管理 可持久化线段树
  • 原文地址:https://www.cnblogs.com/mjtabu/p/11887746.html
Copyright © 2011-2022 走看看