本文基于SpringBoot前后端分离架构,介绍如何使用Hutool提供的工具类导出Excel表格。

Hutool官网:http://hutool.cn/docs/#/poi/Excel%E5%B7%A5%E5%85%B7-ExcelUtil

准备工作

引入关键依赖。

<dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.6</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>${poi.version}</version></dependency>

Controller

@Api(tags = "Excel导出")@Controller@RequestMapping("/export")public class ExportController {@Resourceprivate HgOrderInfoService orderService;@PostMapping("/order")public void exportExcel(@RequestBody PageOrderRo pageOrderRo, HttpServletResponse response) throws IOException {orderService.exportExcel(pageOrderRo, response);}}

Service

省略了部分代码,仅展示核心的关键代码。

public void exportExcel(PageOrderRo pageOrderRo, HttpServletResponse response) throws IOException {// 获取数据orderInfoVos = baseMapper.listInService(pageOrderRo);// 导出表格(true:使用xlsx格式的表格)ExcelWriter writer = ExcelUtil.getWriter(true);// 设置列的别名writer.addHeaderAlias("patientName", "服务对象").addHeaderAlias("phonenum", "联系方式").addHeaderAlias("departmentName", "科室").addHeaderAlias("orderNo", "单据号");// 设置标题行writer.merge(4, "测试标题", true);// 设置单元格:仅写入别名行、冻结首行writer.setOnlyAlias(true).setFreezePane(1);// 设置日期格式DataFormat dataFormat = writer.getWorkbook().createDataFormat();writer.getStyleSet().getCellStyleForDate().setDataFormat(dataFormat.getFormat(DatePattern.NORM_DATETIME_PATTERN));// 写入表格writer.write(orderInfoVos, true);// 设置输出流response.setContentType("application/vnd.ms-excel;charset=utf-8");// filename为导出时的默认文件名(解决中文乱码问题)String filename = URLEncoder.encode("测试.xlsx", "UTF-8").replaceAll("\\+", "%20");response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + filename);ServletOutputStream out = response.getOutputStream();// 写到输出流后关闭工作簿writer.flush(out, true).close();}