后台接收前端excel并解析入库

先来看controller

@PostMapping("/savePersonByExcel")
public ApiResult savePersonByExcel(@RequestParam("file") MultipartFile file) throws Exception {
    
    //TODO: 做一些校验

    File tempFile = File.createTempFile("temp", null);
    file.transferTo(tempFile);
    ExcelParser parser = new ExcelParser();
    List<Person> persons = parser.parseExcel(tempFile);
    tempFile.delete();
    personService.saveAll(persons);
}

这里使用MutipartFile来接收文件,创建临时文件tempFile(用完一定要记得删除),ExcelParser为转换器,以下是详细代码:

import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ExcelContactParser {

    public List<Person> parseExcelToPerson(File file) throws IOException {
        List<Person> persons = new ArrayList<>();

        FileInputStream fis = new FileInputStream(file);
        Workbook workbook = WorkbookFactory.create(fis);
        Sheet sheet = workbook.getSheetAt(0);

        Iterator<Row> rowIterator = sheet.iterator();

        if (rowIterator.hasNext()) {
            rowIterator.next();
        }

        while (rowIterator.hasNext()) {
            Row row = rowIterator.next();

            if (row == null || isRowEmpty(row)) {
                continue;
            }

            Cell cname = row.getCell(0);
            Cell csex = row.getCell(1);
            Cell cage = row.getCell(2);
            Cell cmobile = row.getCell(3);

            YthSmsContacts c = new Person(cname.getStringCellValue()
                    , cmobile.getStringCellValue()
                    , csex.getStringCellValue()
                    , cage.getStringCellValue()
            );
            persons.add(c);
        }

        return persons;
    }

    
    //判断去除空行,很重要
    public static boolean isRowEmpty(Row row) {
        for (int cellNum = row.getFirstCellNum(); cellNum < row.getLastCellNum(); cellNum++) {
            Cell cell = row.getCell(cellNum);
            if (cell != null && cell.getCellType() != CellType.BLANK) {
                return false;
            }
        }
        return true;
    }

    
    //通过判断某个关键列判断数据完整性
    public static boolean isMobileEmpty(Row row) {
        Cell cell = row.getCell(3);
        if (cell == null || cell.getCellType() == CellType.BLANK)
            return true;
        else
            return false;
    }


}

最后按常规方式入库就好了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值