Springboot2模块系列:poi(上传excel保存至数据库)

1 简介

当数据量较大时,向数据库一条条添加数据费时,易出错,使用Excel导入数据较方便,省时省事。

2 Usage

2.1 pom.xml

<dependency>
			<groupId>org.apache.poigroupId>
			<artifactId>poiartifactId>
			<version>3.17version>
		dependency>
		<dependency>
			<groupId>org.apache.poigroupId>
			<artifactId>poi-ooxmlartifactId>
			<version>3.17version>
		dependency>
		<dependency>
			<groupId>commons-iogroupId>
			<artifactId>commons-ioartifactId>
			<version>2.4version>
    dependency>
    <dependency>
			<groupId>commons-fileuploadgroupId>
			<artifactId>commons-fileuploadartifactId>
			<version>1.3.1version>
		dependency>

2.2 数据类

package com.prjname.po;

import java.io.Serializable;

public class Database implements Serializable {
    private String name;
    private String address;
    private String sex;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getAddress() {
        return address;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public String getSex() {
        return sex;
    }
}

2.3 读取Excel内容工具类

package com.prjname.util;

import java.util.List;
import java.util.ArrayList;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
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 org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
import com.prjname.po.Database;

public class ReadExcelUtil {
    public static List readExcel(MultipartFile file) throws Exception {
        List<Database> excelDatas = new ArrayList<>();
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        // 获取文件流
        InputStream ins = file.getInputStream();
        // 文件类
        Workbook wb = null;
        // 文件流读取
        if (suffix.equals("xlsx")) {
            wb = new XSSFWorkbook(ins);
        } else {
            wb = new HSSFWorkbook(ins);
        }
        // 读取文件流中sheet
        Sheet sheet = wb.getSheetAt(0);
        if (null != sheet) {
        	// 读取sheet单元内容,line为行,从第几行开始读取,行编号从0开始
            for (int line = 1; line <= sheet.getLastRowNum(); line++) {
                Database datas = new Database();
                // 每行行内容
                Row row = sheet.getRow(line);
                // 读取行中列内容,列从0开始编号
                String name = row.getCell(0).getStringCellValue();
                String address = row.getCell(1).getStringCellValue();
                String sex = row.getCell(2).getStringCellValue();
                datas.setName(name);
                datas.setAddress(address);
                datas.setSex(sex);
                excelDatas.add(datas);
            }
        }
        return excelDatas;
    }
}

2.4 路由层

package com.prjname.controller;

import com.prjname.service.DatabaseService;
import com.prjname.po.Database;
import com.prjname.util.ReadExcelUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.util.httpUtil.HttpClientUtil;
import com.xhwl.util.httpsUtil.*;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;
import java.util.List;
import java.util.Arrays;
import java.util.ArrayList;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/v1/databases")
public class DatasController {
    static Logger logger = LoggerFactory.getLogger(DatasController.class);
    @Autowired
    private DatabaseService databaseService;

    @RequestMapping(value = "/import-excel", method = RequestMethod.POST)
    public Map importExcel(@RequestParam(value = "filename") MultipartFile file) {
        Map returnMap = new HashMap();
        try {
            List<Database> returnLi = ReadExcelUtil.readExcel(file);
            for (Database datas : returnLi) {
                databaseService.addDatas(datas);
            }
            returnMap.put("code", 200);
            returnMap.put("msg", "SUCCESS");
            returnMap.put("infos", returnLi);
            return returnMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        returnMap.put("code", 400);
        returnMap.put("msg", "ERROR");
        returnMap.put("infos", "检查参数");
        return returnMap;
    } 
}

2.5 Postman测试

Springboot2模块系列:poi(上传excel保存至数据库)_第1张图片

图2.1 导入数据请求方式

【参考文献】
[1]https://blog.csdn.net/qq_37231511/article/details/93756623

你可能感兴趣的:(#,单体服务SpringBoot2)