package cn.chnmuseum.party.common.util;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.InputStream;
import java.util.*;

public class ImportExcelUtil {

    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("格式不对");
        }
    }

    public static List<Map<String, String>> readExcel(String fileName, InputStream is) throws Exception {

        boolean ret = isXls(fileName);
        Workbook workbook;
        // 根据文件后缀创建不同的对象
        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();

        List<Map<String, String>> list = new ArrayList<>();

        for (int i = 1; i <= lastRowNum; i++) {
            HashMap<String, String> map = new LinkedHashMap<>();
            //获取行数据
            Row row = sheet.getRow(i);
            for (int j = 0; j < lastCellNum; j++) {
                //获取单元格
                Cell cell = row.getCell(j);
                if (cell != null) {
                    cell.setCellType(CellType.STRING);
                    //cell.setCellFormula(CellType.STRING.name());
                    //列名 :数据
                    map.put(titleRow.getCell(j).getStringCellValue(), cell.getStringCellValue());
                }
            }
            list.add(map);
        }
        is.close();
        return list;
    }

}