ExcelUtils.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. * Copyright (c) 2018 佳缘科技 All rights reserved.
  3. * <p>
  4. * https://www.scjydz.com
  5. * <p>
  6. * 版权所有,侵权必究!
  7. */
  8. package com.wjp.common.utils;
  9. import com.alibaba.excel.EasyExcel;
  10. import com.alibaba.excel.converters.longconverter.LongStringConverter;
  11. import jakarta.servlet.http.HttpServletResponse;
  12. import org.apache.commons.lang3.StringUtils;
  13. import org.springframework.beans.BeanUtils;
  14. import java.io.IOException;
  15. import java.net.URLEncoder;
  16. import java.nio.charset.StandardCharsets;
  17. import java.util.ArrayList;
  18. import java.util.Date;
  19. import java.util.List;
  20. /**
  21. * excel工具类
  22. *
  23. * @author Toby javatangbin@163.com
  24. */
  25. public class ExcelUtils {
  26. /**
  27. * Excel导出
  28. *
  29. * @param response response
  30. * @param fileName 文件名
  31. * @param sheetName sheetName
  32. * @param list 数据List
  33. * @param pojoClass 对象Class
  34. */
  35. public static void exportExcel(HttpServletResponse response, String fileName, String sheetName, List<?> list,
  36. Class<?> pojoClass) throws IOException {
  37. if (StringUtils.isBlank(fileName)) {
  38. //当前日期
  39. fileName = DateUtils.format(new Date());
  40. }
  41. response.setContentType("application/vnd.ms-excel");
  42. response.setCharacterEncoding("UTF-8");
  43. fileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
  44. response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
  45. EasyExcel.write(response.getOutputStream(), pojoClass).registerConverter(new LongStringConverter()).sheet(sheetName).doWrite(list);
  46. }
  47. /**
  48. * Excel导出,先sourceList转换成List<targetClass>,再导出
  49. *
  50. * @param response response
  51. * @param fileName 文件名
  52. * @param sheetName sheetName
  53. * @param sourceList 原数据List
  54. * @param targetClass 目标对象Class
  55. */
  56. public static void exportExcelToTarget(HttpServletResponse response, String fileName, String sheetName, List<?> sourceList,
  57. Class<?> targetClass) throws Exception {
  58. List targetList = new ArrayList<>(sourceList.size());
  59. for (Object source : sourceList) {
  60. Object target = targetClass.newInstance();
  61. BeanUtils.copyProperties(source, target);
  62. targetList.add(target);
  63. }
  64. exportExcel(response, fileName, sheetName, targetList, targetClass);
  65. }
  66. }