springboot使用ExcelBody自定義注解優(yōu)雅實(shí)現(xiàn)Excel導(dǎo)出

我們知道,在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)!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容