我們知道,在springmvc中,我們使用ResponseBody注解修飾在Controller方法上,就可以直接將返回值轉(zhuǎn)化為json返回在頁(yè)面。
于是乎,作者受到了這點(diǎn)啟發(fā),能不能也有個(gè)ExcelBody注解,直接將Controller層方法返回成一個(gè)Excel文件內(nèi)容導(dǎo)出呢,于是著手實(shí)現(xiàn),我們希望在Controller層寫(xiě)如下代碼,即可實(shí)現(xiàn)Excel導(dǎo)出。最終效果:
@RestController
public class StudentController{
@GetMapping("export")
@ExcelBody
public List<Student> exportStudents(){
return studentService.selectAll();
}
}
我們希望在訪問(wèn)上面接口的時(shí)候,即可實(shí)現(xiàn)Excel導(dǎo)出。
具體實(shí)現(xiàn)邏輯:
編寫(xiě)ExcelBody注解:
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelBody {
}
實(shí)現(xiàn)ResponseBodyAdvice,對(duì)ExcelBody注解的Controller層方法做單獨(dú)處理。
這里我們使用的是easyExcel導(dǎo)出excel,當(dāng)然,你也可以使用其他技術(shù)導(dǎo)出。
@ControllerAdvice
public class ExcelResponseBodyAdvice implements ResponseBodyAdvice<List> {
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return methodParameter.getMethodAnnotation(ExcelBody.class)!=null;
}
@Override
public List beforeBodyWrite(List retVal, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse response) {
if(CollectionUtils.isEmpty(retVal)){
return null;
}
//設(shè)置response的Header
response.getHeaders().add("Content-Disposition", "attachment;filename=學(xué)生列表.xlsx");
response.getHeaders().add("Content-Type","application/msexcel;charset=UTF-8");
try {
EasyExcel.write(response.getBody(), retVal.get(0).getClass())
.sheet("學(xué)生列表")
.doWrite(retVal);
response.getBody().flush();
} catch (IOException e) {
throw new MmsException("io流處理異常!",e);
}
return null;
}
}
最后附上學(xué)生類(lèi):
@Data
public class Student{
@ExcelProperty(value = "學(xué)生id",index = 0)
private Integer id;
@ExcelProperty(value = "學(xué)生姓名",index = 1)
private String name;
@ExcelProperty(value = "學(xué)生年齡",index = 2)
private Integer age;
}
最后瀏覽器 訪問(wèn)對(duì)應(yīng)接口,即可實(shí)現(xiàn)excel文件導(dǎo)出。
最后再提一個(gè)建議,如果是excel文件上傳,我們是不是也可以自定義一個(gè)ExcelRequestBody注解,再自定義一個(gè)參數(shù)解析器呢,答案也是可以的,本人已經(jīng)實(shí)現(xiàn)了,各位如果你也有興趣趕緊試試吧,祝讀者好運(yùn)!