数据导出成Excel表格 发表于 2021-11-26 12345678910111213141516171819js复制代码//Controller层@PostMapping(value = "/exportPlanDemandList")@ApiOperation("需求条目导出")@AdviceLog(value = "需求条目导出", type = LogType.OPERATE, operateType = LogOperateType.EXPORT)public void exportDemandList(@RequestBody DemandPlanListVo vo, OutputStream out) { try { String sheetName = "需求条目"; // 获取所需数据的分页 Pager pager = demandPlanListService.getDemandListPage(vo); // 将查询出的数据集合传入 List<Map<String, Object>> list = ConvertUtils.listConvert(pager.getRows()); String[] excelTilte = BasisFormationConstant.excelDemandList2; String[] headerTitle = Arrays.stream(excelTilte).map(e -> e.split(":")[1]).toArray(size -> new String[size]); String[] headerValues = Arrays.stream(excelTilte).map(e -> e.split(":")[0]).toArray(size -> new String[size]); ExcelUtil.exportExcel2007WithSXSSF(sheetName, headerTitle, headerValues, list, out, null); } catch (Exception e) { e.printStackTrace(); }} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147js复制代码public class ConvertUtils { private static final String CHINA_GREEN = "绿色"; private static final String ENG_GREEN = "green"; private static final String CHINA_RED = "红色"; private static final String ENG_RED = "red"; private static final String CHINA_ORANGE = "橙色"; private static final String ENG_ORANGE = "orange"; private static final String CHINA_PURPLE = "紫色"; private static final String ENG_PURPLE = "purple"; private static final String CHINA_YELLOW = "黄色"; private static final String ENG_YELLOW = "yellow"; private static final String CHINA_BLUE = "蓝色"; private static final String ENG_BLUE = "#0c60aa"; /** * list克隆 * * @param sources * @param c * @param <E> * @param <T> * @return */ public static <E, T> List<T> convertList(List<E> sources, Class<T> c) { if (CollectionUtils.isEmpty(sources)) { return new ArrayList<T>(); } List<T> list = new ArrayList<T>(); for (E source : sources) { list.add(convertBean(source, c)); } return list; } /** * param convert entity * @param param * @param tClass * @param <T> * @param <E> * @return */ public static <T, E> T convertBean(E param, Class<T> tClass) { try { if (param == null) { return tClass.newInstance(); } T instance = tClass.newInstance(); BeanUtils.copyProperties(param, instance); return instance; } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); return null; } } public static <T> List<Map<String, Object>> listConvert(List<T> list) { // 定义List<Map<String, Object>>数组<br> // list为外部传进来的list集合 List<Map<String, Object>> list_map = new ArrayList<Map<String, Object>>(); if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) { //PropertyUtils.describe(Object)转换 list.forEach(item -> { Map<String, Object> map = null; try { map = (Map<String, Object>) PropertyUtils.describe(item); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } list_map.add(map); }); } return list_map; } public static String convertBinaryColor(String color){ if(StringUtil.isNotEmpty(color)){ color=color.replace(CHINA_GREEN,ENG_GREEN); color=color.replace(CHINA_RED,ENG_RED); color=color.replace(CHINA_ORANGE,ENG_ORANGE); color=color.replace(CHINA_PURPLE,ENG_PURPLE); color=color.replace(CHINA_YELLOW,ENG_YELLOW); color=color.replace(CHINA_BLUE,ENG_BLUE); } return color; } /** * 特殊将字符串转义 * @param value * @return */ public static String escapeStr(String value) { StringBuffer result=new StringBuffer(); if(value == null){ return null; }else{ char content[] = new char[value.length()]; value.getChars(0, value.length(), content, 0); result = new StringBuffer(content.length + 50); for(int i = 0; i < content.length; i++) switch(content[i]) { case 34: // '"' result.append("""); break; case 38: // '&' result.append("&"); break; case 39: // ''' result.append("'"); break; case 60: // '<' result.append("<"); break; case 62: // '>' result.append(">"); break; default: result.append(content[i]); break; } } return result.toString(); } } 1234567891011121314151617js复制代码// 常量类(表格的类名)public class BasisFormationConstant { public static final String[] excelDemandList2 = new String[] { "num:编号", "demandName:需求名称", "demandCategoryName:需求类别", "demandLevel:对应层级", "demandTypeName:需求验证类型", "demandProduct:承接产品", "remark:说明", "resourceName:需求来源", "verifyStatus:验证状态", "demandStatus:需求状态", "isIcon:是否包含图标", "createTime:创建时间" };} 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473js复制代码public class ExcelUtil { // 2003 版本 最大支持65536 行 public final static String EXCEL_FILE_2003 = "2003"; // 2007 版本以上 最大支持1048576行 public final static String EXCEl_FILE_2007 = "2007"; // 2007 版本以上 大数据量导出 public final static String EXCEl_FILE_2007_SXSSF = "2007_SXSSF"; /** * <p> * 导出无头部标题行Excel <br> * 时间格式默认:yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格标题 * @param headersField 表格字段集合 * @param dataList 数据集合 * @param out 输出流 * @param version 2003 或者 2007,不传时默认生成2003版本 * @throws IOException */ public static void exportExcel(String title, String[] headersField, List<Map<String, Object>> dataList, OutputStream out, String version) throws IOException { if (StringUtils.isEmpty(version) || EXCEL_FILE_2003.equals(version.trim())) { exportExcel2003(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss"); } else if(EXCEl_FILE_2007_SXSSF.equals(version.trim())) { exportExcel2007WithSXSSF(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss"); } else { exportExcel2007(title, null, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss"); } } /** * <p> * 导出带有头部标题行的Excel <br> * 时间格式默认:yyyy-MM-dd hh:mm:ss <br> * </p> * * @param title 表格标题 * @param headers 头部标题集合 * @param headersField 表格头部标题对应的字段集合 * @param dataList 数据集合 * @param out 输出流 * @param version 2003 或者 2007,不传时默认生成2003版本 * @throws IOException */ public static void exportExcel(String title, String[] headers, String[] headersField, List<Map<String, Object>> dataList, OutputStream out, String version) throws IOException { if (StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())) { exportExcel2003(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss"); } else if(EXCEl_FILE_2007_SXSSF.equals(version.trim())) { exportExcel2007WithSXSSF(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss"); } else { exportExcel2007(title, headers, headersField, dataList, out, "yyyy-MM-dd HH:mm:ss"); } } /** * <p> * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br> * 此版本生成2007以上版本的文件 (文件后缀:xlsx) * </p> * * @param title * 表格标题名 * @param headers * 表格头部标题集合 * @param headersField * 表格头部标题对应的字段集合 * @param dataList * 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 * JavaBean属性的数据类型有基本数据类型及String,Date * @param out * 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 * @param pattern * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" * @throws IOException */ public static void exportExcel2007WithSXSSF(String title, String[] headers, String[] headersField, List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException { SXSSFWorkbook workbook = null; try { // 声明一个工作薄 workbook = new SXSSFWorkbook(); // 生成一个表格 Sheet sheet = workbook.createSheet(title); sheet.setDefaultColumnWidth(30); // 生成一个样式 CellStyle headerStyle = workbook.createCellStyle(); // 设置这些样式 headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); // 生成一个字体 org.apache.poi.ss.usermodel.Font font = workbook.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) 16); headerStyle.setFont(font); // 生成并设置另一个样式 CellStyle dataStyle = workbook.createCellStyle(); /* dataStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); dataStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/ // 生成另一个字体 org.apache.poi.ss.usermodel.Font font2 = workbook.createFont(); dataStyle.setFont(font2); // 产生表格标题行 Row row = sheet.createRow(0); Cell cellHeader; if(headers!=null){ for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(headerStyle); cellHeader.setCellValue(new XSSFRichTextString(headers[i])); } } // 遍历集合数据,产生数据行 Iterator<Map<String, Object>> it = dataList.iterator(); Map<String, Object> map; int index = 0; Object value; String textValue; Cell cell; Matcher matcher; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); SimpleDateFormat sdf=null; if(StringUtils.isNotEmpty(pattern)){ sdf = new SimpleDateFormat(pattern); }else{ sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } while (it.hasNext()) { index++; row = sheet.createRow(index); map = (Map<String,Object>) it.next(); for (int n = 0; n < headersField.length; n++) { cell = row.createCell(n); cell.setCellStyle(dataStyle); value = map.get(headersField[n]); // 判断值的类型后进行强制类型转换 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它数据类型都当作字符串简单处理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是数字当作double处理 cell.setCellValue(Double.parseDouble(textValue)); } else { cell.setCellValue(textValue); } } } } workbook.write(out); out.flush(); } catch (IOException e) { e.printStackTrace(); throw e; }finally { if(workbook != null) { try { workbook.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * <p> * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br> * 此版本生成2007以上版本的文件 (文件后缀:xlsx) * </p> * * @param title * 表格标题名 * @param headers * 表格头部标题集合 * @param headersField * 表格头部标题对应的字段集合 * @param dataList * 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 * JavaBean属性的数据类型有基本数据类型及String,Date * @param out * 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 * @param pattern * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" * @throws IOException */ public static void exportExcel2007(String title, String[] headers, String[] headersField, List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException { XSSFWorkbook workbook = null; try { // 声明一个工作薄 workbook = new XSSFWorkbook(); // 生成一个表格 XSSFSheet sheet = workbook.createSheet(title); // 设置表格默认列宽度为30个字节 sheet.setDefaultColumnWidth(30); // 生成一个样式 XSSFCellStyle headerStyle = workbook.createCellStyle(); // 设置这些样式 headerStyle.setFillForegroundColor(new XSSFColor(new Color(217, 217, 217))); // 生成一个字体 XSSFFont font = workbook.createFont(); font.setFontName("宋体"); font.setColor(new XSSFColor(Color.BLACK)); font.setFontHeightInPoints((short) 16); // 把字体应用到当前的样式 headerStyle.setFont(font); // 生成并设置另一个样式 XSSFCellStyle dataStyle = workbook.createCellStyle(); /* dataStyle.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE)); dataStyle.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);*/ // 生成另一个字体 XSSFFont font2 = workbook.createFont(); // 把字体应用到当前的样式 dataStyle.setFont(font2); // 产生表格标题行 XSSFRow row = sheet.createRow(0); XSSFCell cellHeader; if(headers!=null){ for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(headerStyle); cellHeader.setCellValue(new XSSFRichTextString(headers[i])); } } // 遍历集合数据,产生数据行 Iterator<Map<String, Object>> it = dataList.iterator(); Map<String, Object> map; int index = 0; Object value; String textValue; XSSFCell cell; XSSFRichTextString richString; Matcher matcher; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); SimpleDateFormat sdf=null; if(StringUtils.isNotEmpty(pattern)){ sdf = new SimpleDateFormat(pattern); }else{ sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss"); } while (it.hasNext()) { index++; row = sheet.createRow(index); map = (Map<String,Object>) it.next(); for (int n = 0; n < headersField.length; n++) { cell = row.createCell(n); cell.setCellStyle(dataStyle); value = map.get(headersField[n]); // 判断值的类型后进行强制类型转换 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它数据类型都当作字符串简单处理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是数字当作double处理 cell.setCellValue(Double.parseDouble(textValue)); } else { richString = new XSSFRichTextString(textValue); cell.setCellValue(richString); } } } } workbook.write(out); out.flush(); } catch (IOException e) { e.printStackTrace(); throw e; }finally { if(workbook != null) { try { workbook.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * <p> * 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中 <br> * 此方法生成2003版本的excel,文件名后缀:xls <br> * </p> * * @param title * 表格标题名 * @param headers * 表格头部标题集合 * @param headersField * 表格头部标题对应的字段集合 * @param dataList * 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的 * JavaBean属性的数据类型有基本数据类型及String,Date * @param out * 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中 * @param pattern * 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss" * @throws IOException */ public static void exportExcel2003(String title, String[] headers, String[] headersField, List<Map<String, Object>> dataList, OutputStream out, String pattern) throws IOException { HSSFWorkbook workbook = null; try { // 声明一个工作薄 workbook = new HSSFWorkbook(); // 生成一个表格 HSSFSheet sheet = workbook.createSheet(title); // 设置表格默认列宽度为20个字节 sheet.setDefaultColumnWidth(20); // 生成一个样式 HSSFCellStyle headerStyle = workbook.createCellStyle(); // 设置这些样式 // 生成一个字体 HSSFFont font = workbook.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) 11); // 把字体应用到当前的样式 headerStyle.setFont(font); // 生成并设置另一个样式 HSSFCellStyle dataStyle = workbook.createCellStyle(); // 生成另一个字体 HSSFFont font2 = workbook.createFont(); // 把字体应用到当前的样式 dataStyle.setFont(font2); // 产生表格标题行 HSSFRow row = sheet.createRow(0); HSSFCell cellHeader; if(headers!=null && headers.length>0){ for (int i = 0; i < headers.length; i++) { cellHeader = row.createCell(i); cellHeader.setCellStyle(headerStyle); cellHeader.setCellValue(new HSSFRichTextString(headers[i])); } } // 遍历集合数据,产生数据行 Iterator<Map<String,Object>> it = dataList.iterator(); Map<String,Object> map; int index = 0; Object value; String textValue; HSSFCell cell; HSSFRichTextString richString; Matcher matcher; Pattern p = Pattern.compile("^//d+(//.//d+)?$"); SimpleDateFormat sdf = new SimpleDateFormat(pattern); while (it.hasNext()) { index++; row = sheet.createRow(index); map = (Map<String,Object>) it.next(); for (int n = 0; n < headersField.length; n++) { cell = row.createCell(n); cell.setCellStyle(dataStyle); value = map.get(headersField[n]); // 判断值的类型后进行强制类型转换 textValue = null; if (value instanceof Integer) { cell.setCellValue((Integer) value); } else if (value instanceof Float) { textValue = String.valueOf((Float) value); cell.setCellValue(textValue); } else if (value instanceof Double) { textValue = String.valueOf((Double) value); cell.setCellValue(textValue); } else if (value instanceof Long) { cell.setCellValue((Long) value); } if (value instanceof Boolean) { textValue = "是"; if (!(Boolean) value) { textValue = "否"; } } else if (value instanceof Date) { textValue = sdf.format((Date) value); } else { // 其它数据类型都当作字符串简单处理 if (value != null) { textValue = value.toString(); } } if (textValue != null) { matcher = p.matcher(textValue); if (matcher.matches()) { // 是数字当作double处理 cell.setCellValue(Double.parseDouble(textValue)); } else { richString = new HSSFRichTextString(textValue); cell.setCellValue(richString); } } } } workbook.write(out); out.flush(); } catch (IOException e) { e.printStackTrace(); throw e; }finally { if(workbook != null) { try { workbook.close(); } catch (IOException e) { e.printStackTrace(); } } } }} 本文转载自: 掘金 开发者博客 – 和开发相关的 这里全都有