1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
| public class ExcelUtils { private static final String REG = "\\{([a-zA-Z_1-9]+)\\}"; private static final String REG_LIST = "\\{\\.([a-zA-Z_1-9]+)\\}"; private static final Pattern PATTERN = Pattern.compile(REG); private static final Pattern PATTERN_LIST = Pattern.compile(REG_LIST);
private ExcelUtils() { }
public static byte[] writeExcel(String templateFilePath, Map<String, Object> context, List<?> dataList) { ClassPathResource classPathResource = new ClassPathResource(templateFilePath); InputStream inputStream = null;
try { inputStream = classPathResource.getInputStream(); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException("获取模板失败!", e); } try (HSSFWorkbook workbook = new HSSFWorkbook(inputStream)) { Sheet sheet = workbook.getSheetAt(0); int listStartRowNum = -1; for (int i = sheet.getFirstRowNum(); i <= sheet.getLastRowNum(); i++) { Row row = sheet.getRow(i); if (row != null) { for (int j = 0; j < row.getLastCellNum(); j++) { Cell cell = row.getCell(j); if (cell != null && cell.getCellType() == CellType.STRING) { String cellValue = cell.getStringCellValue(); if (listStartRowNum == -1 && cellValue.matches(REG_LIST)) { listStartRowNum = i; }
Object newValue = cellValue; Matcher matcher = PATTERN.matcher(cellValue); while (matcher.find()) { String replaceExp = matcher.group(); String key = matcher.group(1); Object replaceValue = context.get(key); if (replaceValue == null) { replaceValue = ""; } if (replaceExp.equals(cellValue)) { newValue = replaceValue; } else { newValue = ((String) newValue).replace(replaceExp, replaceValue.toString()); } } setCellValue(cell, newValue);
}
}
} } if (-1 != listStartRowNum) { Row listStartRow = sheet.getRow(listStartRowNum); if (CollectionUtils.isEmpty(dataList)) { for (int i = 0; i < listStartRow.getLastCellNum(); i++) { Cell cell = listStartRow.getCell(i); if (cell != null) { cell.setCellValue(""); } } } else { int lastCellNum = listStartRow.getLastCellNum(); if (listStartRowNum + 1 <= sheet.getLastRowNum()) { sheet.shiftRows(listStartRowNum + 1, sheet.getLastRowNum(), dataList.size(), true, false); } for (int i = 0; i < dataList.size(); i++) { JSONObject jsonObj = (JSONObject) JSON.toJSON(dataList.get(i)); int newRowNum = listStartRowNum + i + 1; Row newRow = sheet.createRow(newRowNum); for (int j = 0; j < lastCellNum; j++) { Cell cell = listStartRow.getCell(j);
if (cell != null) { Cell newCell = newRow.createCell(j); newCell.setCellStyle(cell.getCellStyle());
if (cell.getCellType() == CellType.STRING && cell.getStringCellValue().matches(REG_LIST)) { String cellExp = cell.getStringCellValue(); Matcher matcher = PATTERN_LIST.matcher(cellExp); matcher.find(); String key = matcher.group(1); Object newValue = jsonObj.get(key); if (newValue == null) { newValue = ""; } setCellValue(newCell, newValue); } else { CellType cellType = cell.getCellType(); if (cellType == CellType.NUMERIC) { newCell.setCellValue(cell.getNumericCellValue()); } else if (cellType == CellType.BOOLEAN) { newCell.setCellValue(cell.getBooleanCellValue()); } else if (cellType == CellType.STRING) { newCell.setCellValue(cell.getStringCellValue()); } else if (cellType == CellType.FORMULA) { } else { newCell.setCellValue(cell.getStringCellValue()); } } } } } sheet.removeRow(listStartRow); sheet.shiftRows(listStartRowNum + 1, sheet.getLastRowNum(), -1, true, false);
for (int i = 0; i < lastCellNum; i++) { CellRangeAddress mergedRangeAddress = getMergedRangeAddress(sheet, listStartRowNum, i); if (mergedRangeAddress != null) { i = mergedRangeAddress.getLastColumn(); for (int j = 1; j < dataList.size(); j++) { int newRowNum = listStartRowNum + j; sheet.addMergedRegionUnsafe(new CellRangeAddress(newRowNum, newRowNum, mergedRangeAddress.getFirstColumn(), mergedRangeAddress.getLastColumn())); } } } } } sheet.setForceFormulaRecalculation(true); sheet.getPrintSetup().setPaperSize(PrintSetup.A4_PAPERSIZE); sheet.getPrintSetup().setLandscape(true); sheet.setFitToPage(true); sheet.getPrintSetup().setFitWidth((short) 1);
sheet.setAutobreaks(true); ByteArrayOutputStream out = new ByteArrayOutputStream(); workbook.write(out); return out.toByteArray(); } catch (Exception e) { throw new ExcelException("生成excel失败!", e); } }
private static void setCellValue(Cell cell, Object value) { if (value instanceof Number) { cell.setCellValue(Double.parseDouble(value.toString())); } else if (value instanceof Date) { cell.setCellValue((Date) value); } else if (value instanceof String) { cell.setCellValue((String) value); } else if (value instanceof Boolean) { cell.setCellValue((Boolean) value); } else { cell.setCellValue(value.toString()); } }
private static CellRangeAddress getMergedRangeAddress(Sheet sheet, int row, int column) { List<CellRangeAddress> mergedRegions = sheet.getMergedRegions(); for (CellRangeAddress cellAddresses : mergedRegions) { if (row >= cellAddresses.getFirstRow() && row <= cellAddresses.getLastRow() && column >= cellAddresses.getFirstColumn() && column <= cellAddresses.getLastColumn()) { return cellAddresses; } } return null; }
static class ExcelException extends RuntimeException {
private static final long serialVersionUID = -2772261598232964002L;
public ExcelException(String msg, Throwable e) { super(msg, e); }
public ExcelException(String msg) { super(msg); } }
public static void writeToResponse(byte[] bytes, HttpServletRequest request, HttpServletResponse response, String fileName) { try { String userAgent = request.getHeader("User-Agent"); String fileName1 = fileName + ".xls"; String newFilename = URLEncoder.encode(fileName1, "UTF8"); String rtn = "filename=\"" + newFilename + "\""; if (userAgent != null) { userAgent = userAgent.toLowerCase(); if (userAgent.indexOf("IE") != -1) { rtn = "filename=\"" + newFilename + "\""; } else if (userAgent.indexOf("OPERA") != -1) { rtn = "filename*=UTF-8''" + newFilename; } else if (userAgent.indexOf("SAFARI") != -1) { rtn = "filename=\"" + new String(fileName1.getBytes("UTF-8"), "ISO8859-1") + "\""; } else if (userAgent.indexOf("FIREFOX") != -1) { rtn = "filename*=UTF-8''" + newFilename; } }
String headStr = "attachment; " + rtn; response.setContentType("multipart/form-data"); response.setCharacterEncoding("utf-8"); response.setHeader("Content-Disposition", headStr); OutputStream outputStream = response.getOutputStream(); outputStream.write(bytes); outputStream.flush();
} catch (UnsupportedEncodingException e) {
e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
}
}
|