>> {}",multipartFile.getSize());
// 文件输出地址
String filePath = ResourceUtils.getURL("m1-04-boot-file/src/main/resources/file").getPath();
File writeFile = new File(filePath, multipartFile.getOriginalFilename());
multipartFile.transferTo(writeFile);
}
}
使用Postman测试文件批量上传接口:
四、Excel文件
1、Excel创建
基于easyexcel
组件中封装的EasyExcel
工具类,继承自EasyExcelFactory
工厂类,实现Excel单个或多个Sheet
的创建,并且在单个Sheet
中写多个Table
数据表;
@Service
public class ExcelService {
/**
* Excel-写单个Sheet
*/
public static void writeSheet () throws Exception {
// 文件处理
String basePath = getAbsolutePath();
File file = new File(basePath+"/easy-excel-01.xlsx") ;
checkOrCreateFile(file);
// 执行写操作
EasyExcel.write(file).head(DataVO.class)
.sheet(0,"用户信息").doWrite(DataVO.getSheet1List());
}
/**
* Excel-写多个Sheet
*/
public static void writeSheets () throws Exception {
// 文件处理
String basePath = getAbsolutePath();
File file = new File(basePath+"/easy-excel-02.xlsx") ;
checkOrCreateFile(file);
ExcelWriter excelWriter = null;
try {
excelWriter = EasyExcel.write(file).build();
// Excel-Sheet1
WriteSheet writeSheet1 = EasyExcel.writerSheet(0,"分页1").head(DataVO.class).build();
// Excel-Sheet2
WriteSheet writeSheet2 = EasyExcel.writerSheet(1,"分页2").head(DataVO.class).build();
// Excel-Sheet3,写两个Table
WriteSheet writeSheet3 = EasyExcel.writerSheet(2,"分页3").build();
WriteTable dataTable = EasyExcel.writerTable(0).head(DataVO.class).build();
WriteTable dataExtTable = EasyExcel.writerTable(1).head(DataExtVO.class).build();
// 执行写操作
excelWriter.write(DataVO.getSheet1List(), writeSheet1);
excelWriter.write(DataVO.getSheet2List(), writeSheet2);
excelWriter.write(DataVO.getSheet1List(),writeSheet3,dataTable) ;
excelWriter.write(DataExtVO.getSheetList(),writeSheet3,dataExtTable) ;
} catch (Exception e){
e.printStackTrace();
} finally {
if (excelWriter != null){
excelWriter.close();
}
}
}
}
/**
* 实体类,这里的注解会解析为Excel中的表头
*/
public class DataVO {
@ExcelProperty("编号")
private Integer id ;
@ExcelProperty("名称")
private String name ;
@ExcelProperty("手机号")
private String phone ;
@ExcelProperty("城市")
private String cityName ;
@ExcelProperty("日期")
private Date date ;
}
文件效果:
2、Excel读取
对于读取Excel文件来说,则需要根据具体的样式来定了,在easyexcel
组件中还可以添加读取过程的监听器;
@Service
public class ExcelService {
/**
* Excel-读取数据
*/
public static void readExcel () throws Exception {
// 文件处理
String basePath = getAbsolutePath();
File file = new File(basePath+"/easy-excel-01.xlsx") ;
if (!file.exists()){
return ;
}
// 读取数据
List<DataVO> dataList = EasyExcel.read(file).head(DataVO.class)
.sheet(0).headRowNumber(1).doReadSync();
dataList.forEach(System.out::println);
}
/**
* Excel-读取数据使用解析监听器
*/
public static void readExcelListener () throws Exception {
// 文件处理
String basePath = getAbsolutePath();
File file = new File(basePath+"/easy-excel-01.xlsx") ;
if (!file.exists()){
return ;
}
// 读取数据,并且使用解析监听器
DataListener dataListener = new DataListener() ;
List<DataVO> dataSheetList = EasyExcel.read(file,dataListener).head(DataVO.class)
.sheet(0).headRowNumber(1).doReadSync();
dataSheetL