实际项目是前后端分离、微服务架构,后台需要为前端提供接口,实现在前端页面下载特定内容的excel模板,后台使用postman测试接口。

为了保证controller层代码简洁,将业务逻辑实现写于service层,然后再service层调用下载excel模板的工具类(目前我写的工具类不是通用的,以后再修改)。

本篇博客是在上一篇博客( https://blog.csdn.net/weixin_42956047/article/details/89141477
的基础之上继续完成。

在controller层添加接口代码:

    @RequestMapping(value = "/excel/downloadExcel",method = RequestMethod.GET)
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response) throws Exception{
        JSONObject res = new JSONObject();
        String fileName = "template.xls";
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Content-Discription", "attachment;fileName" + new String(fileName.getBytes("UTF-8")));
        OutputStream outputStream = response.getOutputStream();
        upExcelFileService.downloadExcelTemplate(outputStream);
    }

在service层添加的代码(是否需要设置返回值,根据具体业务逻辑修改):

    @Override
    public void downloadExcelTemplate(OutputStream outputStream)throws Exception{
        DownloadExcelUtil.exportExcel(outputStream);
    }

添加下载特定内容的excel模板(可根据自己的业务逻辑修改表格风格和内容):

public class DownloadExcelUtil {

    public static void exportExcel(OutputStream outputStream) throws Exception{
		//可选择模板是.xls格式还是.xlsx格式
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个sheet表,可设置多个sheet
        Sheet sheet = workbook.createSheet("sheet1");
        sheet.setColumnWidth(0,8000 );
        sheet.setColumnWidth(1,8000 );
        sheet.setColumnWidth(2,8000 );

        String []tableHeader = new String[] {"工号","手机号","身份证号"};
        HSSFRow firstRow = (HSSFRow) sheet.createRow((short) 0);
        for(int i = 0; i < tableHeader.length; i++){
            HSSFCell cell = firstRow.createCell((short)i);
            cell.setCellStyle(workbook.createCellStyle());
            cell.setCellValue(tableHeader[i]);
        }
        workbook.write(outputStream);
        System.out.println(outputStream);
        outputStream.flush();
        workbook.close();
    }

}

使用postman测试接口注意选择send and download,否则body框中出现一堆乱码:
在这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐