Java POI 使用封装

1、读取数据

import org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.streaming.SXSSFFormulaEvaluator;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFFormulaEvaluator;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

public final class POIUtils {

    private static FormulaEvaluator getCellFormulaEvaluator(Cell cell) {
        Workbook workbook = cell.getRow().getSheet().getWorkbook();
        FormulaEvaluator evaluator;
        if (workbook instanceof HSSFWorkbook) {
            evaluator = new HSSFFormulaEvaluator(((HSSFWorkbook) workbook));
        } else if (workbook instanceof SXSSFWorkbook) {
            evaluator = new SXSSFFormulaEvaluator(((SXSSFWorkbook) workbook));
        } else if (workbook instanceof XSSFWorkbook) {
            evaluator = new XSSFFormulaEvaluator(((XSSFWorkbook) workbook));
        } else {
            throw new RuntimeException("Workbook类型不正确");
        }
        return evaluator;
    }

    private static String getCellValue(Cell cell) {
        String value = "";
        switch (cell.getCellType()) {
            case _NONE: // 未知类型
            case BLANK: //  空白类型
            case ERROR: //  错误类型
                value = "";
                break;
            case STRING: // 字符串类型
                value = cell.getStringCellValue();
                break;
            case BOOLEAN: // 布尔类型
                value = cell.getBooleanCellValue() ? "true" : "false";
                break;
            case FORMULA: // 公式类型
                FormulaEvaluator evaluator;
                try {
                    evaluator = getCellFormulaEvaluator(cell);
                    value = evaluator.evaluate(cell).formatAsString();
                } catch (Exception e) {
                    value = "";
                }
                break;
            case NUMERIC: // 数值类型
                if (DateUtil.isCellDateFormatted(cell)) {
                    // Date date = DateUtil.getJavaDate(cell.getNumericCellValue());
                    // 数据类型说明
                    // yyyy-MM-dd=>14
                    // yyyy年m月d日=>31
                    // yyyy年m月=>57
                    // m月d日=>58
                    // HH:mm=>20
                    // h时mm分=>32
                    short i = cell.getCellStyle().getDataFormat();
                    SimpleDateFormat format;
                    if (i == 20 || i == 32) {
                        format = new SimpleDateFormat("HH:mm");
                    } else if (i == 14 || i == 31 || i == 57 || i == 58) {
                        format = new SimpleDateFormat("yyyy-MM-dd");
                    } else { // 22
                        format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    }
                    try {
                        value = format.format(cell.getDateCellValue());
                    } catch (Exception e) {
                        value = "";
                    }
                } else {
                    // 解决.0的问题
                    double v = cell.getNumericCellValue();
                    if (v == (long) v) {
                        value = String.valueOf((long) v);
                    } else {
                        value = String.valueOf(v);
                    }
                }
                break;
        }
        return value;
    }

    public static ParseBean parseVertically(File file) throws IOException {
        if (Objects.isNull(file)) {
            throw new RuntimeException("文件为空");
        }
        try (Workbook workbook = WorkbookFactory.create(file)) {
            return parseVertically(workbook);
        }
    }


    public static ParseBean parseVertically(InputStream is) throws IOException {
        if (Objects.isNull(is)) {
            throw new RuntimeException("输入流为空");
        }
        try (Workbook workbook = WorkbookFactory.create(is)) {
            return parseVertically(workbook);
        }
    }


    private static ParseBean parseVertically(Workbook workbook) {
        ParseBean bean = new ParseBean();
        Sheet sheet = workbook.getSheetAt(0);
        bean.setTableName(sheet.getSheetName());
        List columns = new ArrayList<>();
        Map commentMap = new HashMap<>();
        List> values = new ArrayList<>();
        sheet.iterator().forEachRemaining(row -> {
            if (row.getRowNum() == sheet.getFirstRowNum()) { // 头部
                for (Cell cell : row) {
                    headerAssemble(columns, commentMap, cell);
                }
            } else { // 数据
                List valueList = new ArrayList<>();
                for (Cell cell : row) {
                    valueList.add(getCellValue(cell));
                }
                values.add(valueList);
            }
        });
        bean.setColumns(columns);
        bean.setRowKeyRule(commentMap.values().toArray(new String[0]));
        bean.setValues(values);
        return bean;
    }


    public static ParseBean parseHorizontally(File file) throws IOException {
        if (Objects.isNull(file)) {
            throw new RuntimeException("文件为空");
        }
        try (Workbook workbook = WorkbookFactory.create(file)) {
            return parseHorizontally(workbook);
        }
    }


    public static ParseBean parseHorizontally(InputStream is) throws IOException {
        if (Objects.isNull(is)) {
            throw new RuntimeException("输入流为空");
        }
        try (Workbook workbook = WorkbookFactory.create(is)) {
            return parseHorizontally(workbook);
        }
    }


    private static ParseBean parseHorizontally(Workbook workbook) {
        Sheet sheet = workbook.getSheetAt(0);
        List columns = new ArrayList<>();
        Map commentMap = new HashMap<>();
        List> values = new ArrayList<>();
        sheet.iterator().forEachRemaining(row -> {
            // 去掉标题行
            if (row.getRowNum() == sheet.getFirstRowNum()) {
                row.forEach(cell -> {
                    headerAssemble(columns, commentMap, cell);
                    columns.clear();
                });
                return;
            }
            short num = row.getFirstCellNum();
            for (Cell cell : row) {
                int index = cell.getColumnIndex() - num;
                if (index == 0) { // 头部
                    headerAssemble(columns, commentMap, cell);
                } else { // 数据
                    if (values.size() <= index - 1) {
                        values.add(new ArrayList<>());
                    }
                    List list = values.get(index - 1);
                    list.add(getCellValue(cell));
                }
            }
        });
        return new ParseBean(sheet.getSheetName(), columns, commentMap.values().toArray(new String[0]), values);
    }


    private static void headerAssemble(List columns, Map commentMap, Cell cell) {
        String value = cell.getRichStringCellValue().getString();
        columns.add(value);
        // 头部的备注值
        if (Objects.nonNull(cell.getCellComment())) {
            String content = cell.getCellComment().getString().getString().split("\n")[1];
            commentMap.put(value, content);
        }
    }

} 
  

2、导出数据

后期补充

你可能感兴趣的:(Java系列,java,poi)