ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java读取excel文件

2021-12-13 18:05:37  阅读:137  来源: 互联网

标签:java 读取 filePath excel cell sheet null out row


    //分析文件,结果为[[第一行的数据],[第二行的数据],.....]
    public static List<List<String>> analysisSheet(String filePath, int currentSheet) {
        Workbook wb = null;
        Sheet sheet = null;
        Row row = null;
        List<List<String>> list = null;
        String cellData = null;
        wb = readExcel(filePath);
        if (wb != null) {
            //用来存放表中数据
            list = new ArrayList<List<String>>();
            //获取第一个sheet
            sheet = wb.getSheetAt(currentSheet);
            //获取最大行数
            int rownum = sheet.getPhysicalNumberOfRows();
            //获取第一行
            row = sheet.getRow(0);
            //获取最大列数
            int colnum = 0;
            /* 获取最大列数 */
            for(int i = 1; i < rownum; i++){
                row = sheet.getRow(i);
                if(row.getPhysicalNumberOfCells()>colnum){
                    colnum = row.getPhysicalNumberOfCells();
                }
            }
            for (int i = 1; i < rownum; i++) {
                Map<String, String> map = new LinkedHashMap<String, String>();
                row = sheet.getRow(i);
                if (row != null) {
                    List<String> rowData = new ArrayList<>();
                    for (int j = 0; j < colnum; j++) {
                        cellData = (String) getCellFormatValue(row.getCell(j));
                        rowData.add(cellData);
                    }
                    list.add(rowData);
                } else {
                    break;
                }
            }
        }
        return list;
    }

    //读取excel文件
    public static Workbook readExcel(String filePath) {
        Workbook wb = null;
        if (filePath == null) {
            return null;
        }
        String extString = filePath.substring(filePath.lastIndexOf("."));
        InputStream is = null;
        try {
            is = new FileInputStream(filePath);
            if (".xls".equals(extString)) {
                return wb = new HSSFWorkbook(is);
            } else if (".xlsx".equals(extString)) {
                return wb = new XSSFWorkbook(is);
            } else {
                return wb = null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }
    //根据excel文件内容数据的不同类型格式化
    public static Object getCellFormatValue(Cell cell) {
        Object cellValue = null;
        if (cell != null) {
            //判断cell类型
            switch (cell.getCellType()) {
                case Cell.CELL_TYPE_NUMERIC: {
                    cellValue = String.valueOf(cell.getNumericCellValue());
                    break;
                }
                case Cell.CELL_TYPE_FORMULA: {
                    //判断cell是否为日期格式
                    if (DateUtil.isCellDateFormatted(cell)) {
                        //转换为日期格式YYYY-mm-dd
                        cellValue = cell.getDateCellValue();
                    } else {
                        //数字
                        cellValue = String.valueOf(cell.getNumericCellValue());
                    }
                    break;
                }
                case Cell.CELL_TYPE_STRING: {
                    cellValue = cell.getRichStringCellValue().getString();
                    break;
                }
                default:
                    cellValue = "";
            }
        } else {
            cellValue = "";
        }
        return cellValue;
    }
    //写入文件,toExcelMap内容格式为{"第五列":"xxxx","第六列:"xxxx"....}
    public static void writeExcel(ConcurrentHashMap<Integer, LinkedHashMap<String,Object>> toExcelMap, int currentSheet, String filePath) {
        OutputStream out = null;
        try {
            // 读取Excel文档
            Workbook workBook = readExcel(filePath);
            // sheet 对应一个工作页
            Sheet sheet = workBook.getSheetAt(currentSheet);

            /**
             * 往Excel中写新数据
             */
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                try {
                    log.info("写入第{}条", i);
                    Row row = sheet.getRow(i);
                    if (toExcelMap.containsKey(i)) {
                        LinkedHashMap<String, Object> info = toExcelMap.get(i);
                        row.createCell(START_COLUMN).setCellValue(info.get("location") != null ? info.get("location").toString() : null);
                        row.createCell(START_COLUMN + 1).setCellValue(info.get("status") != null ? info.get("status").toString() : null);
                        row.createCell(START_COLUMN + 2).setCellValue(info.get("count") != null ? info.get("count").toString() : null);
                    }
                }catch (Exception e) {
                    errorWriteList.add(e);
                }
            }
            System.out.println(errorWriteList);

            // 创建文件输出流,准备输出电子表格:这个必须有,否则你在sheet上做的任何操作都不会有效
            out = new FileOutputStream(filePath);
            workBook.write(out);
            System.out.println("------- 数据导出成功(filePath"+filePath+") -------");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("------- 数据导出失败 -------");
        } finally {
            try {
                if (out != null) {
                    out.flush();
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

 

标签:java,读取,filePath,excel,cell,sheet,null,out,row
来源: https://www.cnblogs.com/fengzi7314/p/15684521.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有