要实现功能,非空校验,如果为空 则下载错误excel,说明错误原因
导入实体
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelDto implements Serializable{
/**
* 用户名
*/
@ExcelProperty("用户名")
private String userName;
/**
* 地址
*/
@ExcelProperty( "地址")
private String addRess;
/**
* 年龄
*/
@ExcelProperty("年龄")
private Integer age;
}
导出excel 错误数据实体
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ExcelError {
/**
* 行号
*/
@Excel(name = "行号", orderNum = "0")
@ExcelProperty("行号")
private Integer lineNumber;
/**
* 数据
*/
@Excel(name = "数据", orderNum = "1")
@ExcelProperty("数据")
private String data;
/**
* 原因
*/
@Excel(name = "原因", orderNum = "2")
@ExcelProperty("原因")
private String reason;
}
controller
@RequestMapping ("/inexcel")
public void importExcel(MultipartFile file, HttpServletResponse response,Long id) throws IOException {
ImportExcelService iinport = new ImportExcelService(id, response);
try {
// 全部数控
List<ExcelDto> objects = EasyExcel.read(new BufferedInputStream(file.getInputStream()), ExcelDto.class, iinport)
.sheet()
.doReadSync();
// 异常数据
List<ExcelError> errorList = iinport.ret();
if(!CollectionUtils.isEmpty(errorList)){
// 错误数据---发送给前端界面
write(response,errorList);
}
} catch (IOException e) {
e.printStackTrace();
}catch (ExcelAnalysisException e){
e.printStackTrace();
// 此处是查询出哪一行 , 哪一列 数据格式不对导致出问题!!!!!!!!!!!!!!!
if (e.getCause() instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) e.getCause();
String cellMsg = "";
CellData cellData = excelDataConvertException.getCellData();
//这里有一个celldatatype的枚举值,用来判断CellData的数据类型
CellDataTypeEnum type = cellData.getType();
if (type.equals(CellDataTypeEnum.NUMBER)) {
cellMsg = cellData.getNumberValue().toString();
} else if (type.equals(CellDataTypeEnum.STRING)) {
cellMsg = cellData.getStringValue();
} else if (type.equals(CellDataTypeEnum.BOOLEAN)) {
cellMsg = cellData.getBooleanValue().toString();
}
// excel表格:第2行,第3列,数据值为:xa,该数据值不符合要求,请检验后重新导入! 请检查其他的记录是否有同类型的错误!
Integer rowNumber = excelDataConvertException.getRowIndex() + 1;
Integer cellNumber = excelDataConvertException.getColumnIndex()+1;
String errorMsg = String.format("excel表格:第%s行,第%s列,数据值为:%s,该数据值不符合要求,请检验后重新导入! 请检查其他的记录是否有同类型的错误!",rowNumber , cellNumber, cellMsg);
System.out.println(errorMsg);
// 写出字段类型错误文件!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
List<ExcelError> excelErrorList = new ArrayList<>();
excelErrorList.add(new ExcelError(rowNumber,cellMsg ,errorMsg));
write(response,excelErrorList);
}
}
}
public void write(HttpServletResponse response, List<ExcelError> excelErrorList) throws IOException {
WriteToExcel<ExcelError> writeToExcel = new WriteToExcel<>();
writeToExcel.createExcelToWeb(response,
excelErrorList,
Arrays.asList("行号","数据","原因"),
Arrays.asList("lineNumber","data","reason"),
"sheet1",
"异常数据.xlsx");
}
导入数据监听类
public class ImportExcelService extends AnalysisEventListener<ExcelDto> {
private Long Id;
private HttpServletResponse response ;
List<ExcelDto> list = new ArrayList<>();
List<ExcelError> excelErrorList = new ArrayList<>();
// 行号
int number = 0;
public ImportExcelService(Long Id, HttpServletResponse response) {
number = 0;
Id = Id;
response = response;
}
// 每读取一行就调用该方法
@Override
public void invoke(ExcelDto excelDto, AnalysisContext analysisContext) {
if(StringUtils.isEmpty(excelDto.getAddRess()))
{
excelErrorList.add(new ExcelError(number,excelDto.getUserName()
+" - "+excelDto.getAddRess()+" - "+excelDto.getAge(),"address 为空"));
}else if(StringUtils.isEmpty(excelDto.getUserName())){
excelErrorList.add(new ExcelError(number,excelDto.getUserName()
+" - "+excelDto.getAddRess()+" - "+excelDto.getAge(),"username 为空"));
}
list.add(excelDto);
number ++;
}
// 全部读取完成就调用该方法
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
if(!CollectionUtils.isEmpty(excelErrorList)){
}
}
public List<ExcelError> ret(){
return excelErrorList;
}
}
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-spring-boot-starter</artifactId>
<version>4.2.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.0.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>2.1.1</version>
</dependency>
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.5</version>
</dependency>
数据返给前端工具类,直接使用
public class WriteToExcel<T> {
private static XSSFWorkbook workbook;
private static XSSFSheet sheet;
private static XSSFRow row;
private static XSSFCell cell;
private static File file;
/**
*
* @param listData 数据
* @param headList 表头list 例 Arrays.asList("昵称","年龄","地址");
* @param fields 属性list 例 Arrays.asList("name","age");
* @param sheet sheet 名称
* @param url 存储位置 例 C:\Users\Desktop\员工信息-1月.xlsx
*/
public void createExcel( List<T> listData,
List<String> headList,
List<String> fields,
String sheet,
String url) {
//空数据
if(CollectionUtils.isEmpty(listData)){
return;
}
//保存位置null
if(StringUtils.isEmpty(url)){
System.err.println("保存位置null");
return;
}
if(StringUtils.isEmpty(sheet)){
sheet = "sheet1";
}
WriteToExcel<T> writeToExcel = new WriteToExcel<>();
//sheet 页名称
WriteToExcel.setSheet(sheet);
//设置表头
WriteToExcel.createHead(headList);
//设置内容
boolean flag = writeToExcel.createContent(listData,fields);
if(flag){
//写入文件
WriteToExcel.writeToFile(url);
}
}
public void createExcelToWeb(
HttpServletResponse response,
List<T> listData,
List<String> headList,
List<String> fields,
String sheet,
String name) throws IOException {
//空数据
if(CollectionUtils.isEmpty(listData)){
return;
}
//name null
if(StringUtils.isEmpty(name)){
System.err.println(" name null");
return;
}
if(StringUtils.isEmpty(sheet)){
sheet = "sheet1";
}
WriteToExcel<T> writeToExcel = new WriteToExcel<>();
//sheet 页名称
WriteToExcel.setSheet(sheet);
//设置表头
WriteToExcel.createHead(headList);
//设置内容
boolean flag = writeToExcel.createContent(listData,fields);
if(flag){
//写入文件
WriteToExcel.writeToFiletoWeb(response,name);
}
}
//创建sheet页
public static void setSheet(String sheetName) {
workbook = new XSSFWorkbook();
sheet = workbook.createSheet(sheetName);
}
//创建表头
public static void createHead(List<String> headList) {
//创建表头,也就是第一行
row = sheet.createRow(0);
for (int i = 0; i < headList.size(); i++) {
cell = row.createCell(i);
cell.setCellValue(headList.get(i));
// 宽度
cell.getSheet().setColumnWidth(i,20*256);
//一般格式
XSSFFont font = workbook.createFont();
// 加粗
font.setBold(true);
font.setFontHeightInPoints((short)20);
// 样式对象
XSSFCellStyle style = workbook.createCellStyle();
//背景色
style.setFillForegroundColor(new XSSFColor(new java.awt.Color(80, 142, 198)));
// 填充方式 全部填充
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFont(font);
cell.setCellStyle(style);
}
}
public boolean createContent(List<T> contentList, List<String> fields) {
boolean flag = true;
//创建表内容,从第二行开始
try {
for (int i = 0; i < contentList.size(); i++) {
row = sheet.createRow(i + 1);
//遍历每一个字段
for (int j = 0; j < fields.size(); j++) {
Field f = contentList.get(i).getClass().getDeclaredField(fields.get(j));
f.setAccessible(true);
// 获取属性值
Object field = f.get(contentList.get(i));
// 字段非空
if(ObjectUtil.isNotEmpty(field)){
System.out.println(field);
//object 强转 string
row.createCell(j).setCellValue(field.toString());
}
}
}
}catch (Exception e){
System.err.println("属性获取异常="+e.getMessage() );
flag = false;
}
return flag;
}
//写入文件
public static void writeToFile(String filePath){
file = new File(filePath);
//将文件保存到指定的位置
try {
workbook.write(new FileOutputStream(file));
System.out.println("写入成功");
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//写入文件
public static void writeToFiletoWeb(HttpServletResponse response,String name) throws IOException {
// 5、导出excel
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
ServletOutputStream out = response.getOutputStream();
workbook.write(out);
out.close();
workbook.close();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="te/inexcel" method="post" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit">提交</p>
</form>
</body>
</html>
字段类型错误测试,应为数字类型!!!
(上传文件)
(下载的错误文件!!!)
用户名为空测试!!!
(上传文件)
(下载的错误文件!!!)