SpringBoot实现Excel文件批量上传导入数据库

作者:W_Meng_H 时间:2023-11-29 11:13:44 

Spring boot + Spring data jpa + Thymeleaf
批量插入 + POI读取 + 文件上传

pom.xml:


<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>

upload.html:


<form enctype="multipart/form-data" method="post" action="/upload/excel">
文件
<input type="file" name="file" /> <input type="submit" value="上传" />
</form>

如果自己的项目中使用了Spring  security,页面提交文件之后,会出现403的错误,最快的解决办法,如下:


http.csrf().ignoringAntMatchers("/upload/**").

在security的配置文件中,加入上边的代码即可。当然还有其他的办法,大家可在网上查找。 

Controller:


package org.meng.project.controller;

import org.meng.project.service.ExcelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
*<p><b>上传Controller类</b></p>
*<p> 上传文件的Controller</p>
* @Author MengMeng
* @Date 2018/10/6 </p>
* @version: 0.1
* @since JDK 1.80_144
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
@Autowired
private HttpServletRequest request;

@Autowired
private ExcelService excelService;

//跳转到上传文件的页面
@RequestMapping(value = "", method = RequestMethod.GET)
public String goUpload() {
//跳转到 templates 中tools目录下的 upload.html
return "tools/upload";
}

@RequestMapping(value = "/excel",method = RequestMethod.POST)
public String upload(MultipartFile file, Model model) throws Exception {

boolean flag = excelService.getExcel(file);

if(flag){
 model.addAttribute("Message", "上传成功");
}else{
 model.addAttribute("Message", "上传失败");
}

return "tools/upload";
}

}

Excel实体:


package org.meng.project.entity;

import javax.persistence.*;
import java.io.Serializable;
import java.util.Objects;

/**
* <p><b>用户实体类</b></p>
* @ClassName User
* @Author MengMeng
* @Date 2018/10/6 </p>
* @Version: 0.1
* @Since JDK 1.80_171
*/

@Entity
@Table(name = "test", schema = "project")
public class Excel implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@Column(length=36)
private String id;

@Column(length=45,nullable=false,unique=true)
private String username;

@Column(length=100,nullable=false,unique=true)
private String email;

@Column(length=45,nullable=false)
private String password;

@Column(length=45)
private String role;

public Excel() {
}

public Excel(Excel user){
 this.id = user.getId();
 this.username = user.getUsername();
 this.role = user.getRole();
 this.email = user.getEmail();
 this.password = user.getPassword();
}

//get 和 set
}

Service:


package org.meng.project.service;

import com.alibaba.fastjson.JSON;

import org.meng.project.entity.*;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.Transactional;

/**
*<p><b>Excel的Service类接口</b></p>
*<p> Excel的Service类接口,与Excel有关的业务逻辑方法</p>
* @Author MengMeng
* @Date 2018/10/6 </p>
* @version: 0.1
* @since JDK 1.80_144
*/
public interface ExcelService {

boolean getExcel(MultipartFile file) throws Exception;

}

ServiceImpl:


package org.meng.project.service;

import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.meng.project.entity.*;
import org.meng.project.repository.ExcelRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

/**
* <p><b>Excel的Service类</b></p>
* <p>Excel的Service类,与User有关的业务逻辑方法</p>
* @Author MengMeng
* @Date 2018/10/6
* @version: 0.1
* @since JDK 1.80_144
*/
@Service
public class ExcelServiceImpl implements ExcelService {

@Autowired
private ExcelRepository excelRepository;

@Override
public boolean getExcel(MultipartFile file) throws Exception {
// TODO Auto-generated method stub
List<Excel> list = new ArrayList<Excel>();

//1.得到上传的表
 Workbook workbook2 = WorkbookFactory.create(file.getInputStream());
 //2、获取test工作表
 Sheet sheet2 = workbook2.getSheet("test");
 //获取表的总行数
 int num = sheet2.getLastRowNum();
 //System.out.println(num);
 //总列数
 int col = sheet2.getRow(0).getLastCellNum();

//遍历excel每一行
 for (int j = 0; j <= num; j++) {
 Row row1 = sheet2.getRow(j);

//如果单元格中有数字或者其他格式的数据,则调用setCellType()转换为string类型
 Cell cell1 = row1.getCell(0);
 cell1.setCellType(CellType.STRING);
 //获取表中第i行,第2列的单元格
 Cell cell2 = row1.getCell(1);
 //excel表的第i行,第3列的单元格
 Cell cell3 = row1.getCell(2);
 cell3.setCellType(CellType.STRING);
 Cell cell4 = row1.getCell(3);
 Cell cell5 = row1.getCell(4);

//这里new 一个对象,用来装填从页面上传的Excel数据,字段根据上传的excel决定
 Excel excel= new Excel();
 excel.setId(cell1.getStringCellValue());
 excel.setEmail(cell2.getStringCellValue());
 excel.setPassword(cell3.getStringCellValue());
 excel.setRole(cell4.getStringCellValue());
 excel.setUsername(cell5.getStringCellValue());
 list.add(excel);
}

excelRepository.saveAll(list);
return true;
}
}

注意:需统一数据库和Excel表中数据值的类型,不然会出现Cannot get a STRING value from a NUMERIC cell等错误。

Repository:


package org.meng.project.repository;

import org.meng.project.entity.Excel;
import org.meng.project.repository.base.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

/**
*<p><b>Excel的DAO类接口</b></p>
*<p> Excel的DAO类接口,与Excel有关的持久化操作方法</p>
* @Author MengMeng
* @Date 2018/10/6 </p>
* @version: 0.1
* @since JDK 1.80_144
*/
@Repository
public interface ExcelRepository extends BaseRepository<Excel, String> {

}

即可实现文件上传:

SpringBoot实现Excel文件批量上传导入数据库

来源:https://blog.csdn.net/W_Meng_H/article/details/82954151

标签:SpringBoot,Excel,批量上传
0
投稿

猜你喜欢

  • Android 实现图片生成卷角和圆角缩略图的方法

    2021-08-12 16:14:12
  • java获取当前时间的四种方法代码实例

    2023-11-28 19:22:53
  • Android Lottie实现中秋月饼变明月动画特效实例

    2023-06-19 12:41:17
  • java读取properties配置文件的方法

    2022-02-13 17:15:44
  • c#之利用API函数实现动画窗体的方法详解

    2022-12-07 04:43:24
  • Java多文件以ZIP压缩包导出的实现方法

    2023-10-08 14:05:20
  • c# wpf如何更好的使用Application程序集资源

    2021-09-30 16:22:17
  • volatile与happens-before的关系与内存一致性错误

    2021-12-13 20:25:37
  • 基于IntelliJ IDEA的类注释和方法注释操作

    2023-03-04 02:00:31
  • Android用SharedPreferences实现登录注册注销功能

    2023-03-24 21:50:10
  • 通过FancyView提供 Android 酷炫的开屏动画实例代码

    2023-04-11 11:00:53
  • Java常见问题之javac Hello.java找不到文件的解决方法

    2023-12-15 21:19:45
  • Java开发岗位面试被问到反射怎么办

    2023-01-07 00:09:12
  • 基于TCP异步Socket模型的介绍

    2022-08-05 23:43:25
  • SpringBoot Java后端实现okhttp3超时设置的方法实例

    2022-11-06 04:56:03
  • Java特性之注解和异常 Throwable

    2023-04-22 13:14:53
  • android SDk中常用的java包介绍

    2021-12-18 01:04:45
  • Android编程实现仿美团或淘宝的多级分类菜单效果示例【附demo源码下载】

    2022-09-09 01:38:50
  • C#实现加密与解密详解

    2023-08-11 16:54:42
  • 阿里开源Java诊断工具神器使用及场景详解

    2023-11-06 17:24:21
  • asp之家 软件编程 m.aspxhome.com