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}
新闻热点
疑难解答