java讀取excel文件


    //分析文件,結果為[[第一行的數據],[第二行的數據],.....]
    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();
            }
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM