1. 程式人生 > 其它 >Vue+Java的EXCEL匯出解決方案,供參考

Vue+Java的EXCEL匯出解決方案,供參考

JAVA端

控制器層

    @PostMapping(value = "/export")
    public void exportGraphTemplate(HttpServletResponse response) {
        try {
            @Cleanup ExcelWriter writer = exportService.exportTemplate();
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding(
"utf-8"); response.setHeader("Content-Disposition", "attachment;filename=".concat(String.valueOf(URLEncoder.encode(StrUtil.format("{}.xls", DateUtil.now()), CharsetUtil.UTF_8)))); @Cleanup ServletOutputStream outputStream = response.getOutputStream(); writer.flush(outputStream,
true); } catch (Exception e) { e.printStackTrace(); } }

服務層

    public ExcelWriter exportTemplate() {
        
        ExcelWriter writer = ExcelUtil.getWriter();
        
        try {

            List<String> header = new ArrayList<>();
            header.add(
"表頭1"); header.add("表頭2"); header.add("表頭3"); writer.writeHeadRow(header); List<List<String>> content = new ArrayList<>(); for(int i=0;i<5;i++) { List<String> co = new ArrayList<>(); co.add("內容1"); co.add("內容2"); co.add("內容3"); content.add(co); } writer.write(content); } catch (Exception e) { e.printStackTrace(); } return writer; }

前端

return request({
        url: '/export',
        method: 'post',
        data: {},
        responseType: "blob",
      }).then(
          response => {
            let fileName = '檔名稱.xls'
            const link = document.createElement('a')
            const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' })
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.setAttribute('download', `${decodeURIComponent(fileName)}`)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          },
          error => {
          }
      )

 

 

 

 

搜尋

複製