Java+JS的Excel文件导出代码示例

Java是使用的SpringBoot框架

pom.xml文件引入Excel操作依赖包poi-ooxml

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.1.2</version>
		</dependency>

controller中的接口代码,
    @GetMapping(value = "/excelFile")
    public ResponseEntity<byte[]> ExportExcelFile(HttpServletResponse response){

        byte[] bytes = null;

        try {
            String fileName = "TestExport.xlsx";

            XSSFWorkbook wb = new XSSFWorkbook();
            Sheet sh = wb.createSheet();

            // 标题
            List<String> titles = new ArrayList<>();
            titles.add("测试列1");
            titles.add("测试列2");
            titles.add("测试列3");

            // 设置列宽
            for (int i = 0; i < titles.size(); i++) {
                sh.setColumnWidth(i, 5000);
            }

            try {

                // 写列标题
                Row r = sh.createRow(0);
                int n = 0;
                for(String title : titles)
                {
                    Cell cell = r.createCell(n++, CellType.STRING);
                    cell.setCellValue(new XSSFRichTextString(title));
                }

                // 写数据
                int num = 0;
                for (int i = 1; i < 100; i++)
                {
                    Row row = sh.createRow(i);
                    row.createCell(num++, CellType.STRING).setCellValue("数据1");
                    row.createCell(num++, CellType.STRING).setCellValue("数据2");
                    row.createCell(num++, CellType.STRING).setCellValue("数据3");
                    num = 0;
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            wb.write(os);
            bytes = os.toByteArray();
            response.reset();
            response.setHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return new ResponseEntity<>(bytes, HttpStatus.OK);
    }

前端JS调用Excel导出接口的代码是
  function onExport() {
   // request为对axios的封装,可以改为其他远程访问方法
   request({
        url: `http://localhost:8080/api/v1/test/excelFile`,
        method: 'get',
        responseType: "blob"  // 需要标明返回类型为blob
    }).then(res => {
        const link = document.createElement('a')
        let blob = new Blob([res],{type: 'application/vnd.ms-excel'}); 

        link.style.display = 'none'
        link.href = URL.createObjectURL(blob);
        let now : Date = new Date();
        link.setAttribute('download', "TestExportExcel_" + dateformat(now, "YYYYMMDD_HHmmss"))
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    });
  }

在前端页面中触发onExport方法就可实现Excel导出

上一篇:日期时间常用判断


下一篇:thinkphp5-cookie