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 => {
          }
      )

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM