Java+EasyExcel实现文件上传功能
需求描述
页面中当用户将excel表格上传到服务器后,将该excel文件保存在本地然后在服务器中将excel中的数据读取出来然后存入数据库
实现
0、依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.1.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastJSON</artifactId>
<version>1.2.75</version>
</dependency>
<!-- 糊涂工具类-->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.11</version>
</dependency>
1、编写配置类
文件上传的路径:用户传来的文件存放在哪
# 文件上传
spring:
servlet:
multipart:
max-file-size: 5MB
max-request-size: 50MB
## 文件上传路径
savepath: C:\Users\86186\Desktop\pp
2、文件上传工具类
文件上传时需要使用到的一些方法
public class FileUploadUtil {
public static String getFileSuffix(String filename){
if(filename == null || filename.isEmpty()){
throw new RuntimeException("文件名不能为空,filename:"+filename);
}
return filename.substring(filename.lastIndexOf("."));
}
public static String randomFilename(){
return UUID.randomUUID().toString().replaceAll("-","");
}
public static String randomFilename2(){
return System.currentTimeMillis()+"";
}
public static String randomFilename3(){
return System.currentTimeMillis()+randomFilename();
}
public static void mkdir(String path){
File file = new File(path);
if(!file.exists()){ //不存在
file.mkdirs();
}
}
public static String getTimeFilename(){
SimpleDateFORMat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd-HH-mm-ss");
Date date = new Date(System.currentTimeMillis());
return simpleDateFormat.format(date)+"-"+randomFilename2();
}
}
3、编写Controller
需要接受前端返回回来的文件
@Autowired
private FileUploadService fileUploadService;
@PostMapping("excelImport")
public ResponseData excelImport(MultipartFile file) throws Exception {
// 由于easyExcel所以需要传入fileUploadService对象
String upload = fileUploadService.upload(file,fileUploadService);
return ResponseDataUtil.buildOk(upload);
}
4、编写Service
@Service("fileUploadService")
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {
// 注入environment来获取在配置文件中文件保存的路径
@Autowired
private Environment environment;
// 注入数据层的对象
@Autowired
private productMapper productMapper;
@Override
public String upload(MultipartFile file, FileUploadService fileUploadService) throws Exception {
if (file == null) {
throw new Exception("文件不可以为空");
}
//得到上传的保存路径
String savePath = environment.getProperty("savepath");
//创建目录
FileUploadUtil.mkdir(savePath);
String dbPath = "";
//得到上传的原文件名
String originalFilename = file.getOriginalFilename();
String suffix = FileUploadUtil.getFileSuffix(originalFilename);
String filename = FileUploadUtil.getTimeFilename() + suffix;
dbPath += filename;
//保存
file.transferTo(new File(savePath, filename));
dbPath = savePath +"\\"+ dbPath;
//调用方法进行读取
EasyExcel.read(dbPath, ExcelDTO.class, new PageReadListener<ExcelDTO>(dataList -> {
for (ExcelDTO demoData : dataList) {
log.info("读取到一条数据{}", jsON.toJSONString(demoData));
insert(demoData);
}
})).sheet().doRead();
return dbPath;
}
// 插入数据到数据库中
@Override
public void insert(ExcelDTO excelDTO) {
// 使用hutool工具类将excelDTO类转换成product类,因为product类对应的是数据库中的字段
Product product = BeanUtil.copyProperties(excelDTO, Product.class);
productMapper.insert(product);
}
}
5、编写excel对应的类
@Data
public class ExcelDTO {
@ExcelProperty("药品名称")
private String pname;
@ExcelProperty("药品价格")
private BigDecimal pprice;
@ExcelProperty("药品数量")
private String pcount;
@ExcelProperty("药品描述")
private String pdes;
@ExcelProperty("药品类别")
private Integer ptype;
}
6、创建easyExcel的监听器
ExcelDTO = excel对应的类
fileUploadService = service对象
@Slf4j
@Component
public class DataListener extends AnalysisEventListener<ExcelDTO> {
public FileUploadService fileUploadService;
public DataListener(FileUploadService fileUploadService) {
this.fileUploadService = fileUploadService;
}
public DataListener() {
}
//读取excel内容,一行一行读取
@Override
public void invoke(ExcelDTO excelDTO, AnalysisContext analysisContext) {
if (excelDTO == null) {
try {
throw new Exception("文件数据为空");
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
7、最终效果
以上就是Java+EasyExcel实现文件上传功能的详细内容,更多关于Java EasyExcel文件上传的资料请关注其它相关文章!
相关文章