springboot 解析Excel(栏位与实体类一一对应)

1.调用类

在这里插入图片描述

2.service方法

@Override
public boolean addBatchByFile(MultipartFile file) {
    try {
        File foler = new File(filePath);
        if (!foler.exists()) {
            boolean f = foler.mkdirs();
            if (!f) {
                log.error("批量 foler.mkdirs failed,folder:" + foler.getAbsolutePath());
            }
        }
        String fileNamePath = foler.getAbsolutePath() + File.separator + file.getOriginalFilename();
        File dest = new File(fileNamePath);
        if (!dest.exists()) {
            boolean cf = dest.createNewFile();
            if (cf) {
                FileUtils.copyInputStreamToFile(file.getInputStream(), dest);
            }
        } else {
            log.error("批量补录 dest.createNewFile failed,folder:" + foler.getAbsolutePath());
        }
        List<TestEntity> list = (List<TestEntity>) ExcelUtils.getListByExcel(fileNamePath,TestEntity.class);
        //删除文件
        dest.delete();
        //批量插入
        if (list != null && list.size() > 0) {
            testMapper.insertBatch(list);
            return true;
        } else {
            return false;
        }
        
    } catch (Exception e) {
        log.error("addBatchByFile fail", e);
        return false;
    }
}

3.工具类

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

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.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**.
 * excel工具类
 */
@Slf4j
public class ExcelUtils {

    public static List<?> getListByExcel(String path, Class<?> className) {
        List<?> list = null;
        // 文件类型
        String filetype = path.substring(path.lastIndexOf("."));
        // 读取excel文件
        InputStream in = null;
        // 获取工作簿
        Workbook wb = null;
        try {
            in = new FileInputStream(path);
            if (filetype.equals(".xls")) {
                wb = new HSSFWorkbook(in);
            } else if (filetype.equals(".xlsx")) {
                wb = new XSSFWorkbook(in);
            } else {
                log.error("文件类型必须是xls或xlsx,file=" + path);
                in.close();
                return null;
            }
            // 获取第一个sheet集合
            if (wb.getSheetAt(0) != null) {
                list = getListBySheet(wb.getSheetAt(0), className);
            }
            in.close();
            wb.close();
        } catch (Exception e) {
            log.error("读取文件失败" + path, e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (wb != null) {
                    wb.close();
                }
            } catch (IOException e) {
                log.error("关闭流失败" + path, e);
            }
        }
        return list;
    }

    private static List<?> getListBySheet(Sheet sheet, Class<?> className) {
        List<Object> list = new ArrayList<>();
        // 总行数
        int rows = sheet.getLastRowNum();
        for (int i = 1; i <= rows; i++) {
            try {
                Row row = sheet.getRow(i);
                Object entity = className.newInstance();
                Field[] fields = className.getDeclaredFields();
                int fieldLength = fields.length;
                for (int j = 0; j < fieldLength; j++) {
                    Field field = fields[j];
                    field.setAccessible(true);
                    if (row == null) {
                        break;
                    }
                    Cell cell = row.getCell(j);
                    if (cell != null) {
                        switch (cell.getCellType()) {
                            case NUMERIC: {
                                // 日期
                                if (DateUtil.isCellDateFormatted(cell)) {
                                    field.set(entity, (cell.getDateCellValue()));
                                // 数值
                                } else {
                                    DecimalFormat df = new DecimalFormat("0");
                                    String str = String.valueOf(df.format(cell.getNumericCellValue()));
                                    if (field.getType() == Integer.class) {
                                        if (StringUtils.isNotEmpty(str)) {
                                            String[] strs = str.split("\\.");
                                            if (strs.length > 1 && "0".equals(strs[1])) {
                                                str = strs[0];
                                            }
                                            field.set(entity, Integer.valueOf(str));
                                        }
                                    } else if (field.getType() == String.class) {
                                        String[] strs = str.split("\\.");
                                        if (strs.length > 1 && "0".equals(strs[1])) {
                                            str = strs[0];
                                        }
                                        field.set(entity, str);
                                    } else if (field.getType() == BigDecimal.class) {
                                        BigDecimal amount = new BigDecimal(str);
                                        field.set(entity, amount);
                                    } else if (field.getType() == Date.class) {
                                        if (str.length() > 8) {
                                            str = str.replace("-", "").replace("/", "");
                                            if (str.length() > 8) {
                                                str = str.substring(0, 8);
                                            }
                                        }
                                        field.set(entity, new SimpleDateFormat("yyyyMMdd").parse(str));
                                    } else {
                                        log.info("field.getType()=" + field.getType() + "");
                                        field.set(entity, str);
                                    }
                                }
                                break;
                            }
                            // 字符串
                            case STRING: {
                                String str = cell.toString();
                                if (field.getType() == Date.class) {
                                    Date date = new SimpleDateFormat("yyyyMMdd").parse(str);
                                    field.set(entity, date);
                                } else if (field.getType() == Integer.class) {
                                    if (StringUtils.isNotEmpty(str)) {
                                        String[] strs = str.split("\\.");
                                        if (strs.length > 1 && "0".equals(strs[1])) {
                                            str = strs[0];
                                        }
                                        field.set(entity, Integer.valueOf(str));
                                    }
                                } else if (field.getType() == String.class) {
                                    String[] strs = str.split("\\.");
                                    if (strs.length > 1 && "0".equals(strs[1])) {
                                        str = strs[0];
                                    }
                                    field.set(entity, str);
                                } else if (field.getType() == BigDecimal.class) {
                                    BigDecimal amount = new BigDecimal(str);
                                    field.set(entity, amount);
                                } else {
                                    field.set(entity, str);
                                }
                                break;
                            }
                            default: {
                                break;
                            }
                        }
                    }
                }
                list.add(entity);
            } catch (Exception e) {
                log.error("解析excel异常", e);
                return null;
            }
        }
        return list;
    }

}

4.pom.xml

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.1.2</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-scratchpad</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- FileUtils.class for upload -->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>${commons.io.version}</version>
</dependency>

Guess you like

Origin blog.csdn.net/qq_36434219/article/details/120593187