pom
<!-- 读取文档 --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><!-- https://mvnrepository.com/artifact/org.apache.poi/poi --><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency>
代码
@GetMapping("exportData")public void exportData(HttpServletResponse response) {// 1. 创建工作空间Workbook workbook = new XSSFWorkbook(); // .xlsx 用 XSSFWorkbook
// Workbook workbook = new HSSFWorkbook(); // .xls 用 HSSFWorkbook// 2. 创建工作表Sheet sheet = workbook.createSheet("信息");// 2.1 创建标题行(第一行)Row headerRow = sheet.createRow(0);/* 3. 定义一个字体(建议将定义字体这段代码,提取出来进行封装,后续可以定义各式各样的的字体) */// 3.1 创建字体Font headerFont = workbook.createFont();// 3.2 14号大小headerFont.setFontHeightInPoints((short) 14);/* 4. 声明样式 CellStyle,并设置 */// 4.1 创建 styleCellStyle style = workbook.createCellStyle();// 4.2 将字体设置进 style 对象中style.setFont(headerFont);// 4.3 水平和垂直居中style.setAlignment(HorizontalAlignment.CENTER);style.setVerticalAlignment(VerticalAlignment.CENTER);/* 设置列宽和表头样式 */String[] headers = {"列表", "激活码", "是否使用", "使用用户", "创建人","激活码类型", "创建时间", "激活时间", "到期时间"};for (int i = 0; i < headers.length; i++) {// 设置每一列的宽度sheet.setColumnWidth(i, 230 * 30);// 设置每一列的 style 和 标题Cell headerCell = headerRow.createCell(i);headerCell.setCellStyle(style);headerCell.setCellValue(headers[i]);}/* 读取数据 */List<returnnames> list = selectMemberEffectCode(null,null,null,null,null,null);/* 遍历 */for (int j = 0; j < list.size(); j++) {Row row = sheet.createRow(j + 1);for (int i = 0; i < headers.length; i++) {Cell cell = row.createCell(i);// 每一列的数据与表头对应上if (i == 0) {cell.setCellValue(j+1);} else if (i == 1) {cell.setCellValue(list.get(j).getCode());} else if (i == 2) {cell.setCellValue(list.get(j).getIsuse()?"已使用":"未使用");} else if (i == 3) {cell.setCellValue(list.get(j).getNickname());} else if (i == 4) {cell.setCellValue(list.get(j).getCreateby());}else if (i == 5) {Integer type = list.get(j).getType();if (type==1){cell.setCellValue("年卡");}else if (type==2){cell.setCellValue("月卡");}else {cell.setCellValue("永久卡");}} else if (i == 6) {cell.setCellValue(list.get(j).getCreatedTime());} else if (i == 7) {cell.setCellValue(list.get(j).getActivatedTime());} else {cell.setCellValue(list.get(j).getExpiredTime());}// 这里将每一数据行的样式设置成和表头样式一样的,建议将 style 样式进行封装,根据不同的需求获取不同的样式cell.setCellStyle(style);}}try (OutputStream osOut = response.getOutputStream()) {// 设置响应类型与编码response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("激活码表.xlsx", "UTF-8"));response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"); // .xlsx 用这个
// response.setContentType("application/vnd.ms-excel;charset=utf-8"); // .xls 用这个response.setCharacterEncoding("utf-8");// 将指定的字节写入此输出流workbook.write(osOut);// 刷新此输出流并强制将所有缓冲的输出字节被写出osOut.flush();// 关闭流osOut.close();workbook.close();} catch (IOException e) {e.printStackTrace();}}
结果图
参考文章