栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java 导入excel通用工具类

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java 导入excel通用工具类

java 导入excel通用工具类


提示:以下是本篇文章正文内容,下面案例可供参考

一、定义需要导入的EXCEL模板,EXCEL格式变更,只需要变更对应的枚举信息就可以,如果定义多个EXCEL模板,只要在类中定义多个枚举就行
import lombok.AllArgsConstructor;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


public class ImportExcelTitle {

    @Getter
    @AllArgsConstructor
    public enum ExpertImportExcel {

        
        USER_NAME("姓名", "user_name", 0, true),
        IDNUMBER("身份证号", "idnumber", 0, true),
        PHONENUM("手机号码", "phonenum", 0, true),
        EMAIL("电子邮箱", "email", 0, false),
        ADDRESS("通讯地址", "address", 0, false),
        ;

        
        private final String titleCn;

        
        private final String valueKey;

        
        private final Integer titleLength;

        
        private final Boolean isRequired;

        
        public static Map getKeyValue() {
            return Arrays.stream(ExpertImportExcel.values()).collect(
                    Collectors.toMap(ExpertImportExcel::getTitleCn, ExpertImportExcel::getValueKey));
        }

        
        public static Map getExcelTitle() {
            return Arrays.stream(ExpertImportExcel.values()).collect(
                    Collectors.toMap(ExpertImportExcel::getValueKey, title -> title));
        }

        public static List checkData(ExpertImportExcel taskImportExcel, String value) {
            return checkDataCommon(value, taskImportExcel.getIsRequired(), taskImportExcel.getTitleCn(), taskImportExcel.getTitleLength());
        }
    }

    
    private static List checkDataCommon(String value, Boolean isRequired, String titleCn, Integer titleLength) {
        List result = new ArrayList<>();
        if (Boolean.TRUE.equals(isRequired) && StringUtils.isBlank(value)) {
            result.add(String.format("%s信息未填", titleCn));
        }
        if (titleLength != 0 && value != null && value.length() > titleLength) {
            result.add(String.format("%s过长", titleCn));
        }
        return result;
    }
}
二、导入的excel处理工具类 对导入的excel进行处理,按照上述ImportExcelTitle.java中的配置,将导入的excel转化成List>格式,
package com.hbck.oa.utils.poi.excel;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

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;




@Slf4j
public class ImportExcelUtil {

    private ImportExcelUtil() {
    }

    
    private static final String EXCEL_2003L = ".xls";
    
    private static final String EXCEL_2007U = ".xlsx";

    private static final String GENERAL = "General";

    private static final String M_D_YY = "m/d/yy";

    
    public static List> parseExcel(InputStream in, String fileName, Map titleKey) throws IOException {
        // 根据文件名来创建Excel工作薄
        Workbook work = getWorkbook(in, fileName);
        Sheet sheet;
        Row row;
        Cell cell;
        // 返回数据
        List> ls = new ArrayList<>();
        // 遍历Excel中所有的sheet
        sheet = work.getSheetAt(0);
        if (sheet == null) {
            return ls;
        }
        // 取第一行标题
        Row topRow = sheet.getRow(0);
        if (null == topRow) {
            return ls;
        }
        row = sheet.getRow(0);
        String[] title;
        if (row == null) {
            return ls;
        }
        title = new String[row.getLastCellNum()];
        for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
            cell = row.getCell(y);
            title[y] = String.valueOf(getCellValue(cell));
        }
        // 遍历当前sheet中的所有行
        // 坑:sheet.getLastRowNum()  最后一行行标,比行数小1
        for (int j = 1; j <= sheet.getLastRowNum(); j++) {
            row = sheet.getRow(j);
            Map m = new HashMap<>(row.getLastCellNum());
            // 遍历所有的列
            for (int y = row.getFirstCellNum(); y < row.getLastCellNum(); y++) {
                cell = row.getCell(y);
                String key = title[y].replace(" ", "");
                if (titleKey.get(key) == null) {
                    log.error("导入excel出现错误的标题:" + key);
                    throw new RuntimeException("excel出现错误的标题:" + key);
                }
                m.put(titleKey.get(key), getCellValue(cell).toString().trim());
            }
            ls.add(m);
        }
        work.close();
        return ls;
    }

    
    public static Workbook getWorkbook(InputStream inStr, String fileName) throws IOException {
        Workbook wb;
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        if (EXCEL_2003L.equals(fileType)) {
            // 2003-
            wb = new HSSFWorkbook(inStr);
        } else if (EXCEL_2007U.equals(fileType)) {
            // 2007+
            wb = new XSSFWorkbook(inStr);
        } else {
            throw new RuntimeException("解析的文件格式有误!");
        }
        return wb;
    }

    public static String getCellValue(Cell cell) {
        String value ="";
        // 日期格式化
        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd");
        if (cell == null) {
            return "";
        }

        if (cell.getCellType()==CellType.STRING.getCode()){
            value = cell.getStringCellValue();
        }else if (cell.getCellType() == CellType.BLANK.getCode()) {
            value = "";
        }else if (cell.getCellType() == CellType.NUMERIC.getCode()){
            if (GENERAL.equals(cell.getCellStyle().getDataFormatString())) {
                double cellValue = cell.getNumericCellValue();
                value = replace(String.valueOf(cellValue));
            } else if (M_D_YY.equals(cell.getCellStyle().getDataFormatString())) {
                value = sdf.format(cell.getDateCellValue());
            } else {
                DataFormatter formatter = new DataFormatter();
                // 直接获取到单元格的值
                value = formatter.formatCellValue(cell);
            }
        }

        return value;
    }

    public static String replace(String s) {
        char a = '.';
        if (s.indexOf(a) >= 0) {
            //去掉多余的0
            s = s.replaceAll("0+$", "");
            //如最后一位是.则去掉
            s = s.replaceAll("[.]$", "");
        }
        return s;
    }
}

调用示例

代码如下(示例):

    @ApiOperation(value = "导入用户")
    @PostMapping("/importData")
    public void importData(MultipartFile fileToUpload) {
        List> excelList;
        try {
            excelList = ImportExcelUtil.parseExcel(
                    fileToUpload.getInputStream(),
                    fileToUpload.getOriginalFilename(),
                   ImportExcelTitle.ExpertImportExcel.getKeyValue());
        } catch (IOException e) {
            log.error("解析excel时失败" + e.getMessage());
        }

        for (Map map:excelList) {
            String jsonString = JSON.toJSONString(map);
            OaUserinfo userinfo = JSON.parseObject(jsonString, OaUserinfo.class);
       		
        }
    }


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/864958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号