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 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
| package com.sora.utils.excel;
import cn.afterturn.easypoi.excel.ExcelExportUtil; import cn.afterturn.easypoi.excel.ExcelImportUtil; import cn.afterturn.easypoi.excel.entity.ExportParams; import cn.afterturn.easypoi.excel.entity.ImportParams; import cn.hutool.core.io.IoUtil; import com.sora.utils.ServletUtils; import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletResponse; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.multipart.MultipartFile;
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.HashMap; import java.util.List; import java.util.Map;
public class ExcelUtils {
public static final Logger logger = LoggerFactory.getLogger(ExcelUtils.class);
private static final HashMap<String, String> MIME_MAP = new HashMap<>(){{ put("txt", "text/plain"); put("csv", "text/csv"); put("html", "text/html"); put("css", "text/css"); put("xml", "text/xml"); put("json", "application/json");
put("jpg", "image/jpeg"); put("jpeg", "image/jpeg"); put("png", "image/png"); put("gif", "image/gif"); put("bmp", "image/bmp"); put("svg", "image/svg+xml");
put("mp3", "audio/mpeg"); put("wav", "audio/wav"); put("ogg", "audio/ogg"); put("flac", "audio/flac");
put("mp4", "video/mp4"); put("mov", "video/quicktime"); put("avi", "video/x-msvideo"); put("mkv", "video/x-matroska");
put("pdf", "application/pdf");
put("xls", "application/vnd.ms-excel"); put("xlsx", "application/vnd.ms-excel");
put("doc", "application/msword"); put("docx", "application/msword"); }};
public static <T> void exportToExcel(List<T> list, String fileName, Class<?> cls) {
ExportParams exportParams = new ExportParams(); exportParams.setStyle(ExcelStyle.class);
Workbook workbook = ExcelExportUtil.exportExcel(exportParams, cls, list);
HttpServletResponse response = ServletUtils.getResponse(); response.setContentType("application/vnd.ms-excel"); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); String encodedFileName = null; encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8); response.setHeader("Content-disposition", "attachment;filename=" + encodedFileName + ".xlsx");
try { workbook.write(response.getOutputStream()); workbook.close(); } catch (IOException e) { logger.error("IO写入错误!", e); } }
public static <T> List<T> importExcelToList(MultipartFile multipartFile, Class<T> cls) { File file = null; try { file = File.createTempFile("temp", ".xls"); multipartFile.transferTo(file); } catch (IOException e) { logger.error("[Excel导入失败,IO读写异常!操作类:[{}]", cls); }
return ExcelImportUtil.importExcel(file, cls, new ImportParams()); }
public static void downloadFile(String filePath) { File file = new File(filePath);
String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
String fileSuffix = null; try { fileSuffix = filePath.substring(filePath.lastIndexOf(".") + 1); } catch (Exception e) { logger.error("文件没有后缀名!使用二进制进行下载"); } String contentType = MIME_MAP.get(fileSuffix) == null ? "application/octet-stream" : MIME_MAP.get(fileSuffix);
HttpServletResponse response = ServletUtils.getResponse(); response.setContentType(contentType); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
try (InputStream in = new FileInputStream(file); ServletOutputStream out = response.getOutputStream()) { IoUtil.copy(in, out); } catch (IOException e) { logger.error("下载文件失败!文件路径:[{}]", filePath); } }
public static <K, V> void exportMapToExcel(Map<K, List<V>> map, String fileName) { try { Workbook workbook = new XSSFWorkbook();
createMapSheet(workbook, "数据列表", map);
HttpServletResponse response = ServletUtils.getResponse(); response.reset(); response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setCharacterEncoding(StandardCharsets.UTF_8.toString()); response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8) + ".xlsx");
try (ServletOutputStream out = response.getOutputStream()) { workbook.write(out); out.flush(); } workbook.close(); } catch (Exception e) { logger.error("导出Map数据Excel失败!", e); } }
private static <K, V> void createMapSheet(Workbook workbook, String sheetName, Map<K, List<V>> data) { if (data == null || data.isEmpty()) { return; }
Sheet sheet = workbook.createSheet(sheetName);
CellStyle headerStyle = workbook.createCellStyle(); Font headerFont = workbook.createFont(); headerFont.setBold(true); headerStyle.setFont(headerFont); headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex()); headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); headerStyle.setAlignment(HorizontalAlignment.CENTER);
CellStyle keyStyle = workbook.createCellStyle(); Font keyFont = workbook.createFont(); keyFont.setBold(true); keyStyle.setFont(keyFont); keyStyle.setAlignment(HorizontalAlignment.LEFT); keyStyle.setVerticalAlignment(VerticalAlignment.CENTER);
Row headerRow = sheet.createRow(0); Cell keyHeader = headerRow.createCell(0); Cell valueHeader = headerRow.createCell(1); keyHeader.setCellValue("Key"); valueHeader.setCellValue("Values"); keyHeader.setCellStyle(headerStyle); valueHeader.setCellStyle(headerStyle);
int rowIndex = 1; for (Map.Entry<K, List<V>> entry : data.entrySet()) { K key = entry.getKey(); List<V> values = entry.getValue();
if (values == null || values.isEmpty()) { Row row = sheet.createRow(rowIndex++); Cell keyCell = row.createCell(0); keyCell.setCellValue(key != null ? key.toString() : ""); keyCell.setCellStyle(keyStyle); } else { int startRow = rowIndex; int endRow = rowIndex + values.size() - 1;
for (V value : values) { Row row = sheet.createRow(rowIndex++);
if (row.getRowNum() == startRow) { Cell keyCell = row.createCell(0); keyCell.setCellValue(key != null ? key.toString() : ""); keyCell.setCellStyle(keyStyle); }
Cell valueCell = row.createCell(1); valueCell.setCellValue(value != null ? value.toString() : ""); }
if (values.size() > 1) { sheet.addMergedRegion(new CellRangeAddress( startRow, endRow, 0, 0 )); } } }
sheet.setColumnWidth(0, 25 * 256); sheet.setColumnWidth(1, 40 * 256);
sheet.createFreezePane(0, 1); } }
|