public class ExcelTemplate { /** * 下载Excel模板工具类 * @param response 响应 * @param obj 注解对象 * @param fileName 模板名称 */ public static void downloadExcelTemplate(HttpServletResponse response, Object obj, String fileName) { //获取字段注解的值 List<String> titles = getAnnotationValue(obj); XSSFWorkbook hwb = new XSSFWorkbook(); //创建一个sheet XSSFSheet sheet = hwb.createSheet("测试"); //创建第一行 XSSFRow row = sheet.createRow(0); //创建一个居中格式 XSSFCellStyle style = hwb.createCellStyle(); style.setAlignment(XSSFCellStyle.ALIGN_CENTER); //创建列对象 XSSFCell cell; for (int i = 0; i < titles.size(); i++) { //创建行 cell = row.createCell(i); //给第一行的每一列的单元格设置值 cell.setCellValue(titles.get(i)); //设置一个居中样式 里面有很多样式可以去看官方文档 cell.setCellStyle(style); sheet.setColumnWidth(i, 256 * 30); } try { try { fileName = new String(fileName.getBytes(), "ISO8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } response.setContentType("application/octet-stream;charset=utf-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); response.addHeader("Pargam", "no-cache"); response.addHeader("Cache-Control", "no-cache"); } catch (Exception ex) { ex.printStackTrace(); } ServletOutputStream outputStream = null; try { outputStream = response.getOutputStream(); hwb.write(outputStream); outputStream.flush(); } catch (IOException e) { e.printStackTrace(); } finally { try { outputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 获取@ExcelField注解对象的字段名称以及注解的title值 * -annotationList:存储@ExcelField注解对象的字段名称 */ public static List<String> getAnnotationValue(Object obj) { List<String> annotationList = new ArrayList<>(); Field[] fields = obj.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { fields[i].setAccessible(true); ExcelField annotation = fields[i].getAnnotation(ExcelField.class); if (Objects.isNull(annotation)) continue; String value = annotation.title(); annotationList.add(value); } return annotationList; }}