1、SpringBoot接口导入Excel,MultipartFile转File
public static File convertToFile(MultipartFile multipartFile) throws IOException {
// 将 MultipartFile 转换为 byte[]
byte[] bytes = multipartFile.getBytes();
// 创建一个临时文件
File tempFile = File.createTempFile("temp", null);
// 将 byte[] 写入文件
try (FileOutputStream fos = new FileOutputStream(tempFile)) {
fos.write(bytes);
}
// 返回临时文件
return tempFile;
}
2、导入Easyexcel依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>3.0.5</version>
</dependency>
3、定义接收数据的对象(省略)
4、实现
@GetMapping("/import")
public void importExcel(@RequestPart("file") MultipartFile file) {
if (!isXlsxFile(file)) {
throw new BusinessException("请上传xlsx文件!");
}
File tempFile = null;
try {
tempFile = FileUtil.convertToFile(file);
} catch (IOException e) {
throw new BusinessException("导入数据失败!");
}
List<MsgContactDTO> data = new ArrayList<>();
try {
EasyExcel.read(file.getInputStream(), MsgContactDTO.class, new MsgContactImportListener(contactService)).sheet().doRead();
EasyExcel.write(tempFile).sheet().doWrite(data);
FileUtil.deleteFile(tempFile.getAbsolutePath());
log.info("导入数据成功!{}", JSON.toJSONString(data));
} catch (Exception e) {
throw new BusinessException("导入数据失败!");
}
}
不写listener的形式
public static <T> List<T> read(MultipartFile file, Class<T> head) throws IOException {
return EasyExcel.read(file.getInputStream(), head, null)
.autoCloseStream(false) // 不要自动关闭,交给 Servlet 自己处理
.doReadAllSync();
}
@GetMapping("/import")
public void importExcel(@RequestPart("file") MultipartFile file) {
if (!isXlsxFile(file)) {
throw new BusinessException("请上传xlsx文件!");
}
List<MsgContactDTO> data = new ArrayList<>();
try {
EasyExcel.read(file.getInputStream(), MsgContactDTO.class, new MsgContactImportListener(contactService)).sheet().doRead();
data = ExcelUtil.read(file, MsgContactDTO.class);
log.info("导入数据成功!{}", JSON.toJSONString(data));
} catch (Exception e) {
throw new BusinessException("导入数据失败!");
}
}
步骤1中temp文件会在哪儿呢?
C:\Users\用户名\AppData\Local\Temp\temp6450778678311298703.tmp