在当今互联网行业中,高并发、高性能、高可用是大家的追求。但是在我们服务的后台,总是会有一些需求是关于数据的处理,这就少不了数据表格的导入导出的功能。今天,我们这片博客主要展示一下用POI技术栈导出Excel表格的demo模板。
本篇的Excel导出模板注释比较完善,我这里也就不多说啥了。
---> 首先是我们xls的导出模板,上源码:
/** * @Description : 导出Excel工具类 - 前端获取域名用:window.location.origin * - https://mvnrepository.com/artifact/org.apache.poi/poi 或 https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml * @Author : Future Buddha * @Date: 2022-02-26 06:09 */ @Slf4j public class ExportExcelUtilXls { /** * 导出 * * @param workbook * @param sheet sheet * @param exportParamsDTO 导出所需字段参数 * @param response 响应 */ public static void export(HSSFWorkbook workbook, HSSFSheet sheet, ExportParamsDTO exportParamsDTO, HttpServletResponse response) { List<String> rowNames = exportParamsDTO.getRowNames(); List<ExportDataDTO> voList = exportParamsDTO.getVoList(); // 产生表格标题行 HSSFRow rows = sheet.createRow(0); HSSFCell cellTitle = rows.createCell(0); //设置标题行高度 rows.setHeight((short) (25 * 35)); //获取列头样式对象 HSSFCellStyle columnTopStyle = getColumnTopStyle(workbook); //获取单元格样式对象 HSSFCellStyle style = getStyle(workbook); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (rowNames.size() - 1))); cellTitle.setCellStyle(columnTopStyle); cellTitle.setCellValue(exportParamsDTO.getTitle()); // 将列头设置到sheet的单元格中 setColumnTopVal(rowNames, sheet, columnTopStyle); //设置sheet单元格数据 setVal(voList, sheet, style); // 定义所需列数 int columnNum = rowNames.size(); //让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < columnNum; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { HSSFRow currentRow; //当前行未被使用过 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { HSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == CellType.STRING) { int length = currentCell.getStringCellValue().getBytes().length; if (columnWidth < length) { columnWidth = length; } } } } if (colNum == 0) { sheet.setColumnWidth(colNum, (columnWidth - 2) * 128); } else { sheet.setColumnWidth(colNum, (columnWidth + 4) * 256); } } long timeMills = System.currentTimeMillis(); String fileName = "Excel-" + timeMills + ".xls"; if (Objects.nonNull(response)) { //浏览器导出 String headStr = "attachment; filename=" + fileName + ""; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", headStr); try (OutputStream out = response.getOutputStream()) { workbook.write(out); } catch (IOException e) { log.error(SYSTEM_EXPORT_FAIL_EXCEPTION.getReason(), e); throw new SystemException(SYSTEM_EXPORT_FAIL_EXCEPTION); } } else { //下载到本地 try (FileOutputStream out = new FileOutputStream("/Users/ws/Desktop/" + fileName)) { workbook.write(out); } catch (Exception e) { log.error(SYSTEM_EXPORT_FAIL_EXCEPTION.getReason(), e); throw new SystemException(SYSTEM_EXPORT_FAIL_EXCEPTION); } } } private static void setVal(List<ExportDataDTO> voList, HSSFSheet sheet, HSSFCellStyle style) { for (int i = 0; i < voList.size(); i++) { List<String> obj = ExportExcelUtil.entityToList(voList.get(i)); //创建数据行 HSSFRow row = sheet.createRow(i + 2); //设置高度 row.setHeight((short) (25 * 20)); for (int j = 0; j < obj.size(); j++) { //设置单元格的数据类型 HSSFCell cell = row.createCell(j, CellType.STRING); if (!CollectionUtils.isEmpty(obj)) { //设置单元格的值 cell.setCellValue(obj.get(j)); } //设置单元格样式 cell.setCellStyle(style); } } } private static void setColumnTopVal(List<String> rowNames, HSSFSheet sheet, HSSFCellStyle columnTopStyle) { // 定义所需列数 int columnNum = rowNames.size(); // 在索引2的位置创建行(最顶端的行开始的第二行) HSSFRow rowRowName = sheet.createRow(1); //设置高度 rowRowName.setHeight((short) (25 * 25)); for (int n = 0; n < columnNum; n++) { //创建列头单元格 HSSFCell cellRowName = rowRowName.createCell(n); //设置列头单元格的数据类型 cellRowName.setCellType(CellType.STRING); HSSFRichTextString text = new HSSFRichTextString(rowNames.get(n)); //设置列头单元格的值 cellRowName.setCellValue(text); //设置列头单元格样式 cellRowName.setCellStyle(columnTopStyle); } } /** * 设置列头单元格样式 */ public static HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) { final String fontName = "Courier New"; // 设置字体 HSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short) 15); //字体加粗 font.setBold(Boolean.TRUE); //设置字体名字 font.setFontName(fontName); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(BorderStyle.THIN); //设置底边框颜色; style.setBottomBorderColor(IndexedColors.BLACK.index); //设置左边框; style.setBorderLeft(BorderStyle.THIN); //设置左边框颜色; style.setLeftBorderColor(IndexedColors.BLACK.index); //设置右边框; style.setBorderRight(BorderStyle.THIN); //设置右边框颜色; style.setRightBorderColor(IndexedColors.BLACK.index); //设置顶边框; style.setBorderTop(BorderStyle.THIN); //设置顶边框颜色; style.setTopBorderColor(IndexedColors.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HorizontalAlignment.CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(VerticalAlignment.CENTER); //设置单元格背景颜色 style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); return style; } /** * 设置列数据信息单元格样式 * * @param workbook Xls表格对象 * @return 返回值 */ public static HSSFCellStyle getStyle(HSSFWorkbook workbook) { final String fontName = "Courier New"; HSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short) 12); //设置字体加粗 font.setBold(Boolean.TRUE); //设置字体名称 font.setFontName(fontName); //设置样式; HSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(BorderStyle.THIN); //设置底边框颜色; style.setBottomBorderColor(IndexedColors.BLACK.index); //设置左边框; style.setBorderLeft(BorderStyle.THIN); //设置左边框颜色; style.setLeftBorderColor(IndexedColors.BLACK.index); //设置右边框; style.setBorderRight(BorderStyle.THIN); //设置右边框颜色; style.setRightBorderColor(IndexedColors.BLACK.index); //设置顶边框; style.setBorderTop(BorderStyle.THIN); //设置顶边框颜色; style.setTopBorderColor(IndexedColors.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HorizontalAlignment.CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } }
---> 下面是我们xlsx的导出demo源码
/** * @Description : 导出 xlsx * - https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml * @Author : Future Buddha * @Date: 2022-02-18 16:46 */ @Slf4j public class ExportExcelUtilXlsx { /** * 导出 * * @param workbook * @param sheet sheet * @param exportParamsDTO 导出所需字段参数 * @param response 响应 */ public static void export(XSSFWorkbook workbook, XSSFSheet sheet, ExportParamsDTO exportParamsDTO, HttpServletResponse response) { List<String> rowNames = exportParamsDTO.getRowNames(); List<ExportDataDTO> voList = exportParamsDTO.getVoList(); // 产生表格标题行 XSSFRow rows = sheet.createRow(0); XSSFCell cellTitle = rows.createCell(0); //设置标题行高度 rows.setHeight((short) (25 * 35)); //获取列头样式对象 XSSFCellStyle columnTopStyle = getColumnTopStyle(workbook); //获取单元格样式对象 XSSFCellStyle style = getStyle(workbook); sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, (rowNames.size() - 1))); cellTitle.setCellStyle(columnTopStyle); cellTitle.setCellValue(exportParamsDTO.getTitle() + "_" + exportParamsDTO.getSheetNum()); // 将列头设置到sheet的单元格中 setColumnTopVal(rowNames, sheet, columnTopStyle); //设置sheet单元格数据 setVal(voList, sheet, style); // 定义所需列数 int columnNum = rowNames.size(); //让列宽随着导出的列长自动适应 for (int colNum = 0; colNum < columnNum; colNum++) { int columnWidth = sheet.getColumnWidth(colNum) / 256; for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) { XSSFRow currentRow; //当前行未被使用过 if (sheet.getRow(rowNum) == null) { currentRow = sheet.createRow(rowNum); } else { currentRow = sheet.getRow(rowNum); } if (currentRow.getCell(colNum) != null) { XSSFCell currentCell = currentRow.getCell(colNum); if (currentCell.getCellType() == CellType.STRING) { int length = currentCell.getStringCellValue().getBytes().length; if (columnWidth < length) { columnWidth = length; } } } } if (colNum == 0) { sheet.setColumnWidth(colNum, (columnWidth - 2) * 128); } else { sheet.setColumnWidth(colNum, (columnWidth + 4) * 256); } } long timeMills = System.currentTimeMillis(); String fileName = "Excel-" + timeMills + ".xlsx"; if (Objects.nonNull(response)) { //浏览器导出 String headStr = "attachment; filename=" + fileName + ""; response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", headStr); try (OutputStream out = response.getOutputStream()) { workbook.write(out); } catch (IOException e) { log.error(SYSTEM_EXPORT_FAIL_EXCEPTION.getReason(), e); CommonResult.fail(SYSTEM_EXPORT_FAIL_EXCEPTION); } } else { //下载到本地 try (FileOutputStream out = new FileOutputStream("/Users/ws/Desktop/" + fileName)) { workbook.write(out); } catch (Exception e) { log.error(SYSTEM_EXPORT_FAIL_EXCEPTION.getReason(), e); CommonResult.fail(SYSTEM_EXPORT_FAIL_EXCEPTION); } } } private static void setVal(List<ExportDataDTO> voList, XSSFSheet sheet, XSSFCellStyle style) { for (int i = 0; i < voList.size(); i++) { List<String> obj = ExportExcelUtil.entityToList(voList.get(i)); //创建数据行 XSSFRow row = sheet.createRow(i + 2); //设置高度 row.setHeight((short) (25 * 20)); for (int j = 0; j < obj.size(); j++) { //设置单元格的数据类型 XSSFCell cell = row.createCell(j, CellType.STRING); if (!CollectionUtils.isEmpty(obj)) { //设置单元格的值 cell.setCellValue(obj.get(j)); } //设置单元格样式 cell.setCellStyle(style); } } } private static void setColumnTopVal(List<String> rowNames, XSSFSheet sheet, XSSFCellStyle columnTopStyle) { // 定义所需列数 int columnNum = rowNames.size(); // 在索引2的位置创建行(最顶端的行开始的第二行) XSSFRow rowRowName = sheet.createRow(1); //设置高度 rowRowName.setHeight((short) (25 * 25)); for (int n = 0; n < columnNum; n++) { //创建列头单元格 XSSFCell cellRowName = rowRowName.createCell(n); //设置列头单元格的数据类型 cellRowName.setCellType(CellType.STRING); XSSFRichTextString text = new XSSFRichTextString(rowNames.get(n)); //设置列头单元格的值 cellRowName.setCellValue(text); //设置列头单元格样式 cellRowName.setCellStyle(columnTopStyle); } } /** * 设置列头单元格样式 */ public static XSSFCellStyle getColumnTopStyle(XSSFWorkbook workbook) { final String fontName = "Courier New"; // 设置字体 XSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short) 15); //字体加粗 font.setBold(Boolean.TRUE); //设置字体名字 font.setFontName(fontName); //设置样式; XSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(BorderStyle.THIN); //设置底边框颜色; style.setBottomBorderColor(IndexedColors.BLACK.index); //设置左边框; style.setBorderLeft(BorderStyle.THIN); //设置左边框颜色; style.setLeftBorderColor(IndexedColors.BLACK.index); //设置右边框; style.setBorderRight(BorderStyle.THIN); //设置右边框颜色; style.setRightBorderColor(IndexedColors.BLACK.index); //设置顶边框; style.setBorderTop(BorderStyle.THIN); //设置顶边框颜色; style.setTopBorderColor(IndexedColors.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HorizontalAlignment.CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(VerticalAlignment.CENTER); //设置单元格背景颜色 style.setFillForegroundColor(IndexedColors.PALE_BLUE.getIndex()); style.setFillPattern(FillPatternType.SOLID_FOREGROUND); return style; } /** * 设置列数据信息单元格样式 * * @param workbook Xls表格对象 * @return 返回值 */ public static XSSFCellStyle getStyle(XSSFWorkbook workbook) { final String fontName = "Courier New"; XSSFFont font = workbook.createFont(); //设置字体大小 font.setFontHeightInPoints((short) 12); //设置字体加粗 font.setBold(Boolean.TRUE); //设置字体名称 font.setFontName(fontName); //设置样式; XSSFCellStyle style = workbook.createCellStyle(); //设置底边框; style.setBorderBottom(BorderStyle.THIN); //设置底边框颜色; style.setBottomBorderColor(IndexedColors.BLACK.index); //设置左边框; style.setBorderLeft(BorderStyle.THIN); //设置左边框颜色; style.setLeftBorderColor(IndexedColors.BLACK.index); //设置右边框; style.setBorderRight(BorderStyle.THIN); //设置右边框颜色; style.setRightBorderColor(IndexedColors.BLACK.index); //设置顶边框; style.setBorderTop(BorderStyle.THIN); //设置顶边框颜色; style.setTopBorderColor(IndexedColors.BLACK.index); //在样式用应用设置的字体; style.setFont(font); //设置自动换行; style.setWrapText(false); //设置水平对齐的样式为居中对齐; style.setAlignment(HorizontalAlignment.CENTER); //设置垂直对齐的样式为居中对齐; style.setVerticalAlignment(VerticalAlignment.CENTER); return style; } }
---> 下面是我们的入口类
/** * @Description : 导出入口 * @Author : Future Buddha * @Date: 2022-02-26 06:09 */ @Slf4j public class ExportExcelUtil { public static void main(String[] args) { final String title = "导出demo"; ExportDataDTO.Builder builder = ExportDataDTO.Builder.of(); builder.createTimeFormat(TimeFormatUtil.localDateTimeToString(LocalDateTime.now())).personName("personName") .businessPersonName("businessName").midPersonName("midPersonName").financialName("financialName").legalName("legalName"); ArrayList<ExportDataDTO> list = Lists.newArrayList(); list.add(builder.build()); list.add(builder.build()); ExportParamsDTO.Builder b = ExportParamsDTO.Builder.of(); b.rowNames(getRowNames()).sheetNum(1).title(title).voList(list); CommonResult result = exportData(b.build(), "xlsx", null); System.out.println(result.toString()); } /** * 设置表头 * @return */ private static List<String> getRowNames() { ArrayList<String> list = Lists.newArrayList(); list.add("日期"); list.add("店铺开设人"); list.add("业务人员"); list.add("中台人员"); list.add("财务人员"); list.add("法务人员"); return list; } /** * * @param exportParamsDTO * @param excelSuffix * @param response * @return */ public static CommonResult exportData(ExportParamsDTO exportParamsDTO, String excelSuffix, HttpServletResponse response) { if (!ExcelSuffixEnum.checkSuffix(excelSuffix)) { log.error(SYSTEM_REQUIRED_PARAM_NON_RIGHTFUL_EXCEPTION.getReason() + ": excelSuffix=[{}]", excelSuffix); CommonResult.fail(SYSTEM_REQUIRED_PARAM_NON_RIGHTFUL_EXCEPTION); } List<ExportDataDTO> voList = exportParamsDTO.getVoList(); if (CollectionUtils.isEmpty(voList)) { CommonResult.fail(SYSTEM_DATA_NON_EXIST_EXCEPTION); } Integer sheetNum = exportParamsDTO.getSheetNum(); if (Objects.equals(ExcelSuffixEnum.XLS.getSuffix(), excelSuffix)) { if (Objects.nonNull(sheetNum)) { for (int i = 0; i < sheetNum; i++) { String title = exportParamsDTO.getTitle() + "_" + i; HSSFWorkbook workbook = new HSSFWorkbook(); //创建工作簿 HSSFSheet sheet = workbook.createSheet(title); ExportExcelUtilXls.export(workbook, sheet, exportParamsDTO, response); } } } if (Objects.equals(ExcelSuffixEnum.XLSX.getSuffix(), excelSuffix)) { if (Objects.nonNull(sheetNum)) { for (int i = 0; i < sheetNum; i++) { String title = exportParamsDTO.getTitle() + i; XSSFWorkbook workbook = new XSSFWorkbook(); //创建工作簿 XSSFSheet sheet = workbook.createSheet(title); ExportExcelUtilXlsx.export(workbook, sheet, exportParamsDTO, response); } } } return CommonResult.success(); } public static List<String> entityToList(ExportDataDTO vo) { List<String> list = Lists.newArrayList(); list.add(vo.getCreateTimeFormat()); list.add(vo.getBusinessPersonName()); list.add(vo.getMidPersonName()); list.add(vo.getFinancialName()); list.add(vo.getLegalName()); list.add(vo.getPersonName()); return list; } }
本模板是直接可以使用的,如有问题留言讨论。
笔者作此文的目的是总结下日常工作中的用到的技术,把这些今后能用到的东西归纳到一起,时常翻阅,可使之历久弥新。
本篇文章说的不多,注释也不是说非常的完善,可能有些可以润色或修正的地方,如若发现可以账号留言,大家互相学习!
https://mp.weixin.qq.com/s?__biz=MzUyMzg0OTk0MA==&mid=2247483790&idx=1&sn=20bd5a4c1084ce543300e8267c1b757b&chksm=fa371835cd4091234488d8440e0f9964b7637bab3150eb1ecb6a4ad32243c6df635c73f8fea3&token=1926569917&lang=zh_CN#rd
读书人不论黄道黑道,总以事理为要!