excel读取工具(apache-poi)

1.封装工具


import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
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.DateUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public final class ExcelReader {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelReader.class);
    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("#.##");

    private ExcelReader() {
    }

    public static ExcelReader.ExcelType getExcelType(String fileName) {
        if (StringUtils.isBlank(fileName)) {
            return null;
        } else {
            return fileName.toLowerCase(Locale.CHINESE).endsWith("xlsx") ? ExcelReader.ExcelType.XLSX : ExcelReader.ExcelType.XLS;
        }
    }

    public static List<Map<String, Object>> readToMapList(File file) {
        return readToMapList((File)file, (String[])null);
    }

    public static List<Map<String, Object>> readToMapList(InputStream in, ExcelReader.ExcelType excelType) {
        return readToMapList((InputStream)in, (ExcelReader.ExcelType)excelType, (String[])null);
    }

    public static List<Map<String, Object>> readToMapList(InputStream in, ExcelReader.ExcelType excelType, String[] fields) {
        return readToMapList(in, excelType, fields, 0);
    }

    public static List<Map<String, Object>> readToMapList(File file, String[] fields) {
        return readToMapList(file, fields, 0);
    }

    public static List<Map<String, Object>> readToMapList(File file, String[] fields, Integer sheetIndex) {
        ArrayList dataList = new ArrayList();

        try {
            ExcelReader.ExcelType type = ExcelReader.ExcelType.XLS;
            if (file.getName().toLowerCase(Locale.CHINESE).endsWith("xlsx")) {
                type = ExcelReader.ExcelType.XLSX;
            }

            return readToMapList(new FileInputStream(file), type, fields, sheetIndex);
        } catch (FileNotFoundException var5) {
            LOGGER.error("file not found", var5);
            return dataList;
        }
    }

    public static List<Map<String, Object>> readToMapList(InputStream inputStream, ExcelReader.ExcelType excelType, String[] fields, Integer sheetIndex) {
        ArrayList dataList = new ArrayList();

        try {
            Object wb = ExcelReader.ExcelType.XLSX.equals(excelType) ? new XSSFWorkbook(inputStream) : new HSSFWorkbook(inputStream);

            try {
                int rows;
                HashMap fieldIndex;
                short headerCellCount;
                int i;
                String cellValue;
                int c;
                HashMap dataMap;
                if (ExcelReader.ExcelType.XLSX.equals(excelType) && wb instanceof XSSFWorkbook) {
                    XSSFSheet sheet = ((XSSFWorkbook)wb).getSheetAt(sheetIndex);
                    rows = sheet.getLastRowNum();
                    XSSFRow headerRow = sheet.getRow(0);
                    fieldIndex = new HashMap();
                    headerCellCount = headerRow.getLastCellNum();
                    i = 0;

                    label119:
                    while(true) {
                        if (i >= headerCellCount) {
                            i = 1;

                            while(true) {
                                if (i > rows) {
                                    break label119;
                                }

                                XSSFRow row = sheet.getRow(i);
                                if (row != null) {
                                    dataMap = new HashMap();

                                    for(c = 0; c < headerCellCount; ++c) {
                                        if (fieldIndex.get(c) != null) {
                                            XSSFCell cell = row.getCell(c);
                                            if (cell != null) {
                                                dataMap.put((String)fieldIndex.get(c), getValue(cell));
                                            }
                                        }
                                    }

                                    dataList.add(dataMap);
                                }

                                ++i;
                            }
                        }

                        XSSFCell cell = headerRow.getCell(i);
                        if (cell != null && CellType.STRING.equals(cell.getCellType())) {
                            cellValue = cell.getStringCellValue();
                            if (fields == null || fields.length == 0 || ArrayUtils.contains(fields, cellValue)) {
                                fieldIndex.put(i, cellValue);
                            }
                        }

                        ++i;
                    }
                } else if (wb instanceof HSSFWorkbook) {
                    HSSFSheet sheet = ((HSSFWorkbook)wb).getSheetAt(sheetIndex);
                    rows = sheet.getLastRowNum();
                    HSSFRow headerRow = sheet.getRow(0);
                    fieldIndex = new HashMap();
                    headerCellCount = headerRow.getLastCellNum();
                    i = 0;

                    label149:
                    while(true) {
                        if (i >= headerCellCount) {
                            i = 1;

                            while(true) {
                                if (i > rows) {
                                    break label149;
                                }

                                HSSFRow row = sheet.getRow(i);
                                if (row != null) {
                                    dataMap = new HashMap();

                                    for(c = 0; c < headerCellCount; ++c) {
                                        if (fieldIndex.get(c) != null) {
                                            HSSFCell cell = row.getCell(c);
                                            if (cell != null) {
                                                dataMap.put((String)fieldIndex.get(c), getValue(cell));
                                            }
                                        }
                                    }

                                    dataList.add(dataMap);
                                }

                                ++i;
                            }
                        }

                        HSSFCell cell = headerRow.getCell(i);
                        if (cell != null && CellType.STRING.equals(cell.getCellType())) {
                            cellValue = cell.getStringCellValue();
                            if (fields == null || fields.length == 0 || ArrayUtils.contains(fields, cellValue)) {
                                fieldIndex.put(i, cellValue);
                            }
                        }

                        ++i;
                    }
                }
            } catch (Throwable var17) {
                if (wb != null) {
                    try {
                        ((Workbook)wb).close();
                    } catch (Throwable var16) {
                        var17.addSuppressed(var16);
                    }
                }

                throw var17;
            }

            if (wb != null) {
                ((Workbook)wb).close();
            }
        } catch (IOException var18) {
            LOGGER.error(var18.getLocalizedMessage(), var18);
        }

        return dataList;
    }

    private static Object getValue(Cell cell) {
        CellType cellType = cell.getCellType();
        if (CellType.FORMULA.equals(cellType)) {
            return cell.getCellFormula();
        } else if (CellType.NUMERIC.equals(cellType) && DateUtil.isCellDateFormatted(cell)) {
            return cell.getDateCellValue();
        } else if (CellType.NUMERIC.equals(cellType)) {
            return DECIMAL_FORMAT.format(cell.getNumericCellValue());
        } else {
            return CellType.STRING.equals(cellType) ? cell.getStringCellValue() : null;
        }
    }

    public static String cutZero(String v) {
        if (v.contains(".")) {
            while(true) {
                if (v.lastIndexOf(48) != v.length() - 1) {
                    if (v.lastIndexOf(46) == v.length() - 1) {
                        v = v.substring(0, v.lastIndexOf(46));
                    }
                    break;
                }

                v = v.substring(0, v.lastIndexOf(48));
            }
        }

        return v;
    }

    public static enum ExcelType {
        XLS,
        XLSX;

        private ExcelType() {
        }
    }
}

2.读取excel 例子:


image.png

3.解析代码

ExcelReader.ExcelType type = ExcelReader.ExcelType.XLS;
            if (serviceFile.getName().toLowerCase().endsWith("xlsx")) {
                type = ExcelReader.ExcelType.XLSX;
            }
            try (InputStream inputStream = serviceFile.openInputStream()) {
                List<Map<String, Object>> maps = ExcelReader.readToMapList(inputStream, type, null, 0);
                task.setTotals(maps.size());
                int index = 0;
                for (Map<String, Object> item : maps) {
                    index++;
                    task.setProgress(index);
                    Entity entity = new Entity(ReportDetails.ID);
                    String report = (String) item.get("所属报表");
                    if (StringUtils.isBlank(report)) {
                        task.println("第" + index + "行数据【所属报表】为空");
                        continue;
                    }
                    entity.setProperty("report", report);
                    String columnName = (String) item.get("列名");
                    if (StringUtils.isBlank(columnName)) {
                        task.println("第" + index + "行数据【列名】为空");
                        continue;
                    }
                    entity.setProperty("columnName", columnName);

                    String numberOfLines = (String) item.get("行数");
                    if (StringUtils.isBlank(numberOfLines)) {
                        task.println("第" + index + "行数据【行数】为空");
                        continue;
                    }
                    entity.setProperty("numberOfLines", Convert.toInt(numberOfLines));

                    String sequenceNumber = (String) item.get("顺序号");
                    if (StringUtils.isBlank(sequenceNumber)) {
                        task.println("第" + index + "行数据【顺序号】为空");
                        continue;
                    }
                    entity.setProperty("sequenceNumber", Convert.toInt(sequenceNumber));

                    String rowSpan = (String) item.get("跨行");
                    if (StringUtils.isNotBlank(rowSpan)) {
                        entity.setProperty("rowSpan", Convert.toInt(rowSpan));
                    }

                    String colSpan = (String) item.get("跨列");
                    if (StringUtils.isNotBlank(colSpan)) {
                        entity.setProperty("colSpan", Convert.toInt(colSpan));
                    }

                    String columnKey = (String) item.get("取值key");
                    if (StringUtils.isNotBlank(columnKey)) {
                        entity.setProperty("columnKey", columnKey);
                    }
                    this.entityService.create(entity);
                }
                task.println("读取excels数据条数 ( " + maps.size() + " )");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,219评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,363评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,933评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,020评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,400评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,640评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,896评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,597评论 0 199
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,327评论 1 244
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,581评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,072评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,399评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,054评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,083评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,849评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,672评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,585评论 2 270

推荐阅读更多精彩内容