柯桥增值式服务
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

105 строки
4.0KB

  1. package com.ningdatech.kqapi.common.util;
  2. import cn.hutool.core.io.IoUtil;
  3. import com.ningdatech.basic.exception.BizException;
  4. import freemarker.template.Configuration;
  5. import freemarker.template.Template;
  6. import freemarker.template.TemplateException;
  7. import lombok.extern.slf4j.Slf4j;
  8. import org.apache.http.entity.ContentType;
  9. import org.springframework.core.io.ByteArrayResource;
  10. import javax.servlet.ServletOutputStream;
  11. import javax.servlet.http.HttpServletResponse;
  12. import java.io.*;
  13. import java.math.BigDecimal;
  14. import java.net.URLEncoder;
  15. import java.nio.charset.StandardCharsets;
  16. import java.nio.file.Files;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. import java.util.zip.ZipEntry;
  20. import java.util.zip.ZipOutputStream;
  21. /**
  22. * <p>
  23. * FreemarkerWordUtil
  24. * </p>
  25. *
  26. * @author WendyYang
  27. * @since 2023/7/24
  28. **/
  29. @Slf4j
  30. public class FreemarkerWordUtil {
  31. private static void setDownFileName(HttpServletResponse response, String fileName) {
  32. String fileNameEncoded;
  33. try {
  34. fileNameEncoded = URLEncoder.encode(fileName, "UTF-8");
  35. } catch (UnsupportedEncodingException e) {
  36. throw new RuntimeException("文件名编码异常");
  37. }
  38. response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileNameEncoded);
  39. }
  40. private static final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_31);
  41. static {
  42. CONFIGURATION.setDefaultEncoding("UTF-8");
  43. CONFIGURATION.setClassForTemplateLoading(FreemarkerWordUtil.class, "/template");
  44. }
  45. /**
  46. * 生成word文件
  47. *
  48. * @param dataMap word中需要展示的动态数据,用map集合来保存
  49. * @param templateName word模板名称,例如:test.ftl
  50. * @param filePath 文件生成的目标路径,例如:D:/wordFile/
  51. * @param fileName 生成的文件名称,例如:test.doc
  52. */
  53. public static void create(Object dataMap, String templateName, String filePath, String fileName) {
  54. try {
  55. Template template = CONFIGURATION.getTemplate(templateName);
  56. //输出文件
  57. File outFile = new File(filePath + File.separator + fileName);
  58. //如果输出目标文件夹不存在,则创建
  59. if (!outFile.getParentFile().exists()) {
  60. boolean ignore = outFile.getParentFile().mkdirs();
  61. }
  62. //将模板和数据模型合并生成文件
  63. Writer out = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(outFile.toPath()), StandardCharsets.UTF_8));
  64. //生成文件
  65. template.process(dataMap, out);
  66. IoUtil.flush(out);
  67. IoUtil.close(out);
  68. } catch (Exception e) {
  69. log.error("根据模版生成Word文件失败:", e);
  70. throw BizException.wrap("根据模版生成Word文件失败");
  71. }
  72. }
  73. public static void export(String fileName, Object data, HttpServletResponse response, String templateName) throws TemplateException, IOException {
  74. Template template = CONFIGURATION.getTemplate(templateName);
  75. response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
  76. response.setContentType(ContentType.APPLICATION_JSON.getMimeType());
  77. setDownFileName(response, fileName);
  78. try (StringWriter out = new StringWriter();
  79. Writer writer = new BufferedWriter(out, 4096)) {
  80. template.process(data, writer);
  81. try (InputStream is = new ByteArrayResource(out.toString().getBytes(StandardCharsets.UTF_8)).getInputStream();
  82. ServletOutputStream outputStream = response.getOutputStream()) {
  83. // 缓冲区
  84. byte[] buffer = new byte[1024];
  85. int bytesToRead;
  86. // 通过循环将读入的Word文件的内容输出到浏览器中
  87. while ((bytesToRead = is.read(buffer)) != -1) {
  88. outputStream.write(buffer, 0, bytesToRead);
  89. }
  90. }
  91. }
  92. }
  93. }