1. public class ExcelTemplate {
    2. /**
    3. * 下载Excel模板工具类
    4. * @param response 响应
    5. * @param obj 注解对象
    6. * @param fileName 模板名称
    7. */
    8. public static void downloadExcelTemplate(HttpServletResponse response, Object obj, String fileName) {
    9. //获取字段注解的值
    10. List<String> titles = getAnnotationValue(obj);
    11. XSSFWorkbook hwb = new XSSFWorkbook();
    12. //创建一个sheet
    13. XSSFSheet sheet = hwb.createSheet("测试");
    14. //创建第一行
    15. XSSFRow row = sheet.createRow(0);
    16. //创建一个居中格式
    17. XSSFCellStyle style = hwb.createCellStyle();
    18. style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
    19. //创建列对象
    20. XSSFCell cell;
    21. for (int i = 0; i < titles.size(); i++) {
    22. //创建行
    23. cell = row.createCell(i);
    24. //给第一行的每一列的单元格设置值
    25. cell.setCellValue(titles.get(i));
    26. //设置一个居中样式 里面有很多样式可以去看官方文档
    27. cell.setCellStyle(style);
    28. sheet.setColumnWidth(i, 256 * 30);
    29. }
    30. try {
    31. try {
    32. fileName = new String(fileName.getBytes(), "ISO8859-1");
    33. } catch (UnsupportedEncodingException e) {
    34. e.printStackTrace();
    35. }
    36. response.setContentType("application/octet-stream;charset=utf-8");
    37. response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
    38. response.addHeader("Pargam", "no-cache");
    39. response.addHeader("Cache-Control", "no-cache");
    40. } catch (Exception ex) {
    41. ex.printStackTrace();
    42. }
    43. ServletOutputStream outputStream = null;
    44. try {
    45. outputStream = response.getOutputStream();
    46. hwb.write(outputStream);
    47. outputStream.flush();
    48. } catch (IOException e) {
    49. e.printStackTrace();
    50. } finally {
    51. try {
    52. outputStream.close();
    53. } catch (IOException e) {
    54. e.printStackTrace();
    55. }
    56. }
    57. }
    58. /**
    59. * 获取@ExcelField注解对象的字段名称以及注解的title值
    60. * -annotationList:存储@ExcelField注解对象的字段名称
    61. */
    62. public static List<String> getAnnotationValue(Object obj) {
    63. List<String> annotationList = new ArrayList<>();
    64. Field[] fields = obj.getClass().getDeclaredFields();
    65. for (int i = 0; i < fields.length; i++) {
    66. fields[i].setAccessible(true);
    67. ExcelField annotation = fields[i].getAnnotation(ExcelField.class);
    68. if (Objects.isNull(annotation)) continue;
    69. String value = annotation.title();
    70. annotationList.add(value);
    71. }
    72. return annotationList;
    73. }
    74. }