package com.sercurityControl.decision.utils; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.CellRangeAddressList; import org.apache.poi.util.Units; import org.apache.poi.xssf.usermodel.*; import org.springframework.util.ObjectUtils; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; import java.util.Base64; import java.util.List; import java.util.Map; public class ExcelExportUtil { public ExcelExportUtil() { } private XSSFWorkbook workbook; /** * @param data 数据集 类型String * @param headList 表头集合 * @param colWidths 列宽 */ public static void excelFileExport(HttpServletResponse response, String fileName, List> data, List> headList, List colWidths) { excelFileExport(response, fileName, data, headList,null, colWidths,null,null); } public static void excelFileExport(HttpServletResponse response, String fileName, List> data, List> headList, List colWidths,List validationList, List validationColList) { excelFileExport(response, fileName, data, headList,null, colWidths,validationList,validationColList); } public static void excelFileExport(HttpServletResponse response, String fileName, List> data, List> headList,List mergeList, List colWidths) { excelFileExport(response, fileName, data, headList,mergeList,colWidths,null,null); } /** * @param fileName 文件名 * @param data 数据集 * @param headList 表头集合 * @param mergeList 合并规则集合(数组长度只能为4) * @param colWidths 列宽 * @param values 下拉选择项 * @param colList 下拉列集合 */ public static void excelFileExport(HttpServletResponse response, String fileName, List> data, List> headList, List mergeList, List colWidths,List values, List colList) { try { String encodeFileName = URLEncoder.encode(fileName, "UTF-8"); response.addHeader("Content-Disposition", "attachment; filename=\"" + encodeFileName + "\""); ExcelExportUtil excel = new ExcelExportUtil(); InputStream input = excel.getExcelFile(data, headList, mergeList, colWidths,values, colList); XSSFWorkbook wb = new XSSFWorkbook(input); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"); OutputStream ouputStream = response.getOutputStream(); wb.write(ouputStream); ouputStream.flush(); ouputStream.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 创建行元素 * * @param style 样式 * @param height 行高 * @param value 行显示的内容 * @param row1 起始行 * @param row2 结束行 * @param col1 起始列 * @param col2 结束列 */ private void createRow(XSSFCellStyle style, XSSFSheet sheet, int height, String value, int row1, int row2, int col1, int col2) { sheet.addMergedRegion(new CellRangeAddress(row1, row2, col1, col2)); //设置从第row1行合并到第row2行,第col1列合并到col2列 XSSFRow rows = sheet.createRow(row1); //设置第几行 rows.setHeight((short) height); //设置行高 XSSFCell cell = rows.createCell(col1); //设置内容开始的列 cell.setCellStyle(style); //设置样式 cell.setCellValue(value); //设置该行的值 } /** * 创建样式 * * @param fontSize 字体大小 * @param bold 是否加粗 * @return style */ private XSSFCellStyle getStyle(int fontSize, boolean bold, boolean border) { Font font = workbook.createFont(); font.setFontName("宋体"); font.setFontHeightInPoints((short) fontSize);// 字体大小 if (bold) { font.setBold(true); } XSSFCellStyle style = (XSSFCellStyle) workbook.createCellStyle(); style.setFont(font); //设置字体 style.setAlignment(HorizontalAlignment.CENTER); // 左右居中2 居右3 默认居左 style.setVerticalAlignment(VerticalAlignment.CENTER);// 上下居中1 XSSFDataFormat format = workbook.createDataFormat(); style.setDataFormat(format.getFormat("@")); style.setWrapText(true); if (border) { style.setBorderRight(BorderStyle.MEDIUM); style.setBorderLeft(BorderStyle.MEDIUM); style.setBorderBottom(BorderStyle.MEDIUM); style.setBorderTop(BorderStyle.MEDIUM); style.setLocked(true); } return style; } /** * 根据数据集生成Excel,并返回Excel文件流 * * @param data 数据集 * @return ba * @throws IOException io异常 */ public InputStream getExcelFile(List> data, List> headList, List mergeList, List colWidths,List values, List colList) throws IOException { try { workbook = new XSSFWorkbook(); XSSFCellStyle cellStyle = getStyle(14, false, true); XSSFSheet sheet = workbook.createSheet("Sheet1"); int startRow = createHeadCell(sheet, headList, mergeList, colWidths); setCellData(data, sheet, cellStyle, startRow); if (ObjectUtils.isEmpty(data) && !ObjectUtils.isEmpty(values)){ for (int i = 0; i < values.size(); i++) { setDropDownBox("Sheet1",values.get(i),colList.get(i),startRow); } } ByteArrayOutputStream baos = new ByteArrayOutputStream(); workbook.write(baos); byte[] ba = baos.toByteArray(); return new ByteArrayInputStream(ba); } catch (Exception e) { e.printStackTrace(); return null; } finally { data = null; if (workbook != null) { workbook.close(); } } } /** * 创建表头 * */ private int createHeadCell(XSSFSheet sheet, List> headList, List mergeList, List colWidths) { /*创建表头*/ XSSFCellStyle cellStyle = getStyle(15, false, true); for (int i = 0; i < headList.size(); i++) { XSSFRow row2 = sheet.createRow(i); row2.setHeight((short) 0x289); for (int j = 0; j < headList.get(i).size(); j++) { XSSFCell tempCell = row2.createCell(j); tempCell.setCellValue(headList.get(i).get(j)); tempCell.setCellStyle(cellStyle); if (colWidths != null && j < colWidths.size() && i == 0) { sheet.setColumnWidth(j, 10 * colWidths.get(j)); } } } /*合并单元格 * merge[0], merge[1] 行合并 相等为不合并 * merge[2], merge[3] 列合并 */ if (!ObjectUtils.isEmpty(mergeList)) { for (int[] merge : mergeList) { if (merge.length == 4) { sheet.addMergedRegion(new CellRangeAddress(merge[0], merge[1], merge[2], merge[3])); } } } // 从哪一行开始渲染表体 return headList.size(); } /** * 创建表体数据 * * @param data 表体数据 * @param cellStyle 样式 * @param startRow 开始行 */ private void setCellData(List> data, XSSFSheet sheet, XSSFCellStyle cellStyle, int startRow) { XSSFRow row = null; XSSFCell cell = null; if (data != null && data.size() > 0) { for (List rowData : data) { row = sheet.createRow(startRow); row.setHeight((short) 0xB99); for (int j = 0; j < rowData.size();j++) { cell = row.createCell(j); cell.setCellStyle(cellStyle); cell.setCellType(CellType.STRING); cell.setCellValue(rowData.get(j) == null ? "" : String.valueOf(rowData.get(j))); } startRow++; } } else { for (int j = startRow; j < startRow + 100; j++) { row = sheet.createRow(j); row.setHeight((short) 0x299); for (int i = 0; i < sheet.getRow(0).getLastCellNum(); i++) { cell = row.createCell(i); cell.setCellStyle(cellStyle); cell.setCellType(CellType.STRING); cell.setCellValue(""); } } } } private void setDropDownBox(String sheetName, String[] values, Integer col,int startRow) { //获取所有sheet页个数 int sheetTotal = workbook.getNumberOfSheets(); //处理下拉数据 if (values != null && values.length != 0) { //新建一个sheet页 String hiddenSheetName = "hiddenSheet"; XSSFSheet hiddenSheet = workbook.getSheet(hiddenSheetName); if (hiddenSheet == null) { hiddenSheet = workbook.createSheet(hiddenSheetName); sheetTotal++; } // 获取数据起始行 int startRowNum = hiddenSheet.getLastRowNum() + 1; int endRowNum = startRowNum; //写入下拉数据到新的sheet页中 for (String value : values) { hiddenSheet.createRow(endRowNum++).createCell(0).setCellValue(value); } //将新建的sheet页隐藏掉 workbook.setSheetHidden(sheetTotal - 1, true); //获取新sheet页内容 String strFormula = hiddenSheetName + "!$A$" + ++startRowNum + ":$A$" + endRowNum; // 设置下拉 XSSFSheet mainSheet = workbook.getSheet(sheetName); mainSheet.addValidationData(setDataValidation(strFormula, mainSheet, col, col,startRow)); } } private DataValidation setDataValidation(String strFormula, XSSFSheet mainSheet, int firstCol, int endCol,int startRow) { CellRangeAddressList regions = new CellRangeAddressList(startRow, startRow + 100, firstCol, endCol); DataValidationHelper dvHelper = mainSheet.getDataValidationHelper(); DataValidationConstraint dataValidationConstraint = dvHelper.createFormulaListConstraint(strFormula); DataValidation validation = dvHelper.createValidation(dataValidationConstraint, regions); validation.setSuppressDropDownArrow(true); return validation; } }