ImportExcelUtil.java 1.95 KB
Newer Older
liqin's avatar
liqin committed
1
package cn.chnmuseum.party.common.util;
2 3

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
liqin's avatar
liqin committed
4
import org.apache.poi.ss.usermodel.*;
5 6 7
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
liqin's avatar
liqin committed
8
import java.util.*;
9 10

public class ImportExcelUtil {
liqin's avatar
liqin committed
11

12 13 14 15 16 17 18 19 20 21 22
    public static boolean isXls(String fileName) {
        // (?i)忽略大小写
        if (fileName.matches("^.+\\.(?i)(xls)$")) {
            return true;
        } else if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
            return false;
        } else {
            throw new RuntimeException("格式不对");
        }
    }

liqin's avatar
liqin committed
23
    public static List<Map<String, String>> readExcel(String fileName, InputStream is) throws Exception {
24 25

        boolean ret = isXls(fileName);
liqin's avatar
liqin committed
26
        Workbook workbook;
27 28 29 30 31 32 33 34 35 36 37 38 39 40
        // 根据文件后缀创建不同的对象
        if (ret) {
            workbook = new HSSFWorkbook(is);
        } else {
            workbook = new XSSFWorkbook(is);
        }
        Sheet sheet = workbook.getSheetAt(0);
        // 得到标题行
        Row titleRow = sheet.getRow(0);
        //行数
        int lastRowNum = sheet.getLastRowNum();
        //列数
        int lastCellNum = titleRow.getLastCellNum();

liqin's avatar
liqin committed
41
        List<Map<String, String>> list = new ArrayList<>();
42 43

        for (int i = 1; i <= lastRowNum; i++) {
liqin's avatar
liqin committed
44
            HashMap<String, String> map = new LinkedHashMap<>();
45 46 47 48 49
            //获取行数据
            Row row = sheet.getRow(i);
            for (int j = 0; j < lastCellNum; j++) {
                //获取单元格
                Cell cell = row.getCell(j);
liqin's avatar
liqin committed
50
                if (cell != null) {
wzp's avatar
wzp committed
51
                    cell.setCellType(CellType.STRING);
liqin's avatar
liqin committed
52
                    //cell.setCellFormula(CellType.STRING.name());
53 54 55 56 57 58 59 60 61
                    //列名 :数据
                    map.put(titleRow.getCell(j).getStringCellValue(), cell.getStringCellValue());
                }
            }
            list.add(map);
        }
        is.close();
        return list;
    }
liqin's avatar
liqin committed
62

63
}