当前位置:   article > 正文

按照模板生成文件,Word 或者 Excel

按照模板生成文件,Word 或者 Excel

需求流程:

    

模板部分如图:

Web端技术选用Jfinal

功能实现:

下面代码是调用 --“外部接口”--传参,将前端选中的信息传给后端, 另外将后端返回的文件流下载成文件

  1. package ibasic.web.com.controller;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.BufferedReader;
  5. import java.io.ByteArrayOutputStream;
  6. import java.io.File;
  7. import java.io.FileInputStream;
  8. import java.io.FileOutputStream;
  9. import java.io.IOException;
  10. import java.io.InputStream;
  11. import java.io.InputStreamReader;
  12. import java.io.OutputStream;
  13. import java.net.URLDecoder;
  14. import java.text.SimpleDateFormat;
  15. import java.util.Date;
  16. import javax.servlet.annotation.MultipartConfig;
  17. import javax.servlet.annotation.WebServlet;
  18. import javax.servlet.http.HttpServlet;
  19. import javax.servlet.http.HttpServletRequest;
  20. import javax.servlet.http.HttpServletResponse;
  21. import org.apache.http.HttpResponse;
  22. import org.apache.http.HttpStatus;
  23. import org.apache.http.client.HttpClient;
  24. import org.apache.http.client.config.RequestConfig;
  25. import org.apache.http.client.methods.HttpPost;
  26. import org.apache.http.entity.StringEntity;
  27. import org.apache.http.impl.client.HttpClientBuilder;
  28. import org.apache.http.message.BasicHeader;
  29. import org.apache.http.protocol.HTTP;
  30. import com.jfinal.kit.PropKit;
  31. import net.sf.json.JSONObject;
  32. //excel模板
  33. @MultipartConfig
  34. @WebServlet("/templateExportServlet")
  35. public class TemplateExportServlet extends HttpServlet{
  36. @Override
  37. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  38. // String data = req.getParameter("data");
  39. BufferedReader header = req.getReader();
  40. StringBuffer sb = new StringBuffer();
  41. String str ="" ;
  42. //将数据读到StringBuffer里面
  43. while (null != (str = header.readLine())){
  44. sb.append( str );
  45. }
  46. // String params = sb.toString().replaceAll("%(?![0-9a-fA-F]{2})", "%25").replaceAll("\\+", "%2B");
  47. // String content = URLDecoder.decode(params,"UTF-8");
  48. JSONObject jsonData = JSONObject.fromObject(sb.toString());
  49. String url = PropKit.get("template_url");
  50. RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build();
  51. HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
  52. HttpPost post = new HttpPost(url);
  53. post.setHeader("Content-Type", "application/json");
  54. String result = "";
  55. try {
  56. StringEntity s = new StringEntity(jsonData.toString(), "utf-8");
  57. s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
  58. post.setEntity(s);
  59. HttpResponse httpResponse = client.execute(post);
  60. InputStream inStream = httpResponse.getEntity().getContent();
  61. // BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
  62. // StringBuilder strber = new StringBuilder();
  63. // String line = null;
  64. // while ((line = reader.readLine()) != null){
  65. // strber.append(line);
  66. // }
  67. // inStream.close();
  68. // result = strber.toString();
  69. // System.out.println(result);
  70. if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
  71. System.out.println("请求服务端失败");
  72. }
  73. // if(!"".equals(result)){
  74. String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
  75. String fileName = String.format("%s.xlsx", now);
  76. getFileByBytes(toByteArray(inStream), PropKit.get("excel_dir"), fileName);
  77. download(PropKit.get("excel_dir")+fileName, resp);
  78. // }
  79. } catch (Exception e) {
  80. e.printStackTrace();
  81. }
  82. }
  83. public HttpServletResponse download(String path, HttpServletResponse response) {
  84. try {
  85. // path是指欲下载的文件的路径。
  86. File file = new File(path);
  87. // 取得文件名。
  88. String filename = file.getName();
  89. // 取得文件的后缀名。
  90. String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
  91. // 以流的形式下载文件。
  92. InputStream fis = new BufferedInputStream(new FileInputStream(path));
  93. byte[] buffer = new byte[fis.available()];
  94. fis.read(buffer);
  95. fis.close();
  96. // 清空response
  97. // response.reset();
  98. // 设置response的Header
  99. response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
  100. response.addHeader("Content-Length", "" + file.length());
  101. OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
  102. response.setContentType("application/octet-stream");
  103. toClient.write(buffer);
  104. toClient.flush();
  105. toClient.close();
  106. } catch (IOException ex) {
  107. ex.printStackTrace();
  108. }
  109. return response;
  110. }
  111. /**
  112. * 将Byte数组转换成文件
  113. **/
  114. public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
  115. BufferedOutputStream bos = null;
  116. FileOutputStream fos = null;
  117. File file = null;
  118. try {
  119. File dir = new File(filePath);
  120. // 判断文件目录是否存在
  121. if (!dir.exists() && dir.isDirectory()) {
  122. dir.mkdirs();
  123. }
  124. file = new File(filePath + File.separator + fileName);
  125. fos = new FileOutputStream(file);
  126. bos = new BufferedOutputStream(fos);
  127. bos.write(bytes);
  128. } catch (Exception e) {
  129. e.printStackTrace();
  130. } finally {
  131. if (bos != null) {
  132. try {
  133. bos.close();
  134. } catch (IOException e) {
  135. e.printStackTrace();
  136. }
  137. }
  138. if (fos != null) {
  139. try {
  140. fos.close();
  141. } catch (IOException e) {
  142. e.printStackTrace();
  143. }
  144. }
  145. }
  146. }
  147. public static byte[] toByteArray(InputStream input) throws IOException {
  148. ByteArrayOutputStream output = new ByteArrayOutputStream();
  149. byte[] buffer = new byte[1024*4];
  150. int n = 0;
  151. while (-1 != (n = input.read(buffer))) {
  152. output.write(buffer, 0, n);
  153. }
  154. return output.toByteArray();
  155. }
  156. }

下面代码实现,接收参数,生成按照模板的文件, SpringBoot实现,将模板文件ftl 放在resource目录下即可。 最后 打成jar 。部署一个地方,将这个服务的ip:port/接口名 告知上面的web去调用即可

  1. package com.wenge.controller;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.wenge.model.Vo;
  5. import com.wenge.util.ExcelUtils;
  6. import org.springframework.beans.factory.annotation.Value;
  7. import org.springframework.core.io.FileSystemResource;
  8. import org.springframework.http.HttpHeaders;
  9. import org.springframework.http.MediaType;
  10. import org.springframework.http.ResponseEntity;
  11. import org.springframework.web.bind.annotation.PostMapping;
  12. import org.springframework.web.bind.annotation.RequestBody;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.File;
  16. import java.io.FileInputStream;
  17. import java.text.SimpleDateFormat;
  18. import java.util.*;
  19. /**
  20. * @description:
  21. * @author: hezha
  22. */
  23. @RestController
  24. public class ExcelControll {
  25. @Value("${excel.dir}")
  26. private String dir_path ;
  27. @PostMapping("/downLoadExcel")
  28. public byte[] downLoadExcel(@RequestBody String data){
  29. String msg = "";
  30. Map<String, Object> dataMap = new HashMap<>();
  31. List<Vo> list = new ArrayList<>();
  32. try {
  33. JSONObject json = JSONObject.parseObject(data);
  34. if(json.containsKey("news")){
  35. JSONArray newsArr = json.getJSONArray("news");
  36. for (int i = 0; i < newsArr.size(); i++) {
  37. Vo vo = new Vo();
  38. JSONObject jsonObject = newsArr.getJSONObject(i);
  39. vo.setId(i+1);
  40. vo.setTitle(jsonObject.getString("title"));
  41. list.add(vo);
  42. }
  43. }
  44. dataMap.put("list", list);
  45. String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
  46. String fileName = String.format("%s.xlsx", now);
  47. System.out.println("当前导出的excel文件---->"+dir_path+fileName);
  48. ExcelUtils.buildExcelByTemplate("templates/excel_template.xlsx", dir_path+fileName, dataMap);
  49. // return dir_path+fileName;
  50. return getBytesByFile(dir_path+fileName);
  51. } catch (Exception e) {
  52. msg = "error";
  53. e.printStackTrace();
  54. }
  55. // return msg;
  56. return null;
  57. }
  58. //将文件转换成Byte数组
  59. public byte[] getBytesByFile(String pathStr) {
  60. File file = new File(pathStr);
  61. System.out.println("文件大小为: " + file.length());
  62. try {
  63. FileInputStream fis = new FileInputStream(file);
  64. ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
  65. byte[] b = new byte[1024];
  66. int n;
  67. while ((n = fis.read(b)) != -1) {
  68. bos.write(b, 0, n);
  69. }
  70. fis.close();
  71. byte[] data = bos.toByteArray();
  72. bos.close();
  73. return data;
  74. } catch (Exception e) {
  75. e.printStackTrace();
  76. }
  77. return null;
  78. }
  79. }

 

  1. package com.wenge.controller;
  2. import com.alibaba.fastjson.JSONArray;
  3. import com.alibaba.fastjson.JSONObject;
  4. import com.spire.doc.Document;
  5. import com.spire.doc.FileFormat;
  6. import com.spire.doc.Section;
  7. import com.spire.doc.collections.SectionCollection;
  8. import com.spire.doc.documents.HorizontalAlignment;
  9. import com.spire.doc.documents.Paragraph;
  10. import com.wenge.model.Vo;
  11. import freemarker.template.Configuration;
  12. import freemarker.template.Template;
  13. import org.springframework.beans.factory.annotation.Value;
  14. import org.springframework.web.bind.annotation.PostMapping;
  15. import org.springframework.web.bind.annotation.RequestBody;
  16. import org.springframework.web.bind.annotation.RestController;
  17. import java.io.*;
  18. import java.text.SimpleDateFormat;
  19. import java.util.*;
  20. /**
  21. * @description:
  22. * @author: hezha
  23. */
  24. @RestController
  25. public class WordController {
  26. @Value("${word3.dir}")
  27. private String dir_word3;
  28. @Value("${word1.dir}")
  29. private String dir_word1;
  30. @PostMapping("/downLoadWord3")
  31. public byte[] word3(@RequestBody String data){
  32. String msg = "";
  33. Map<String, Object> dataMap = new HashMap<>();
  34. List<Vo> list = new ArrayList<>();
  35. try {
  36. JSONObject json = JSONObject.parseObject(data);
  37. if(json.containsKey("news")){
  38. JSONArray newsArr = json.getJSONArray("news");
  39. for (int i = 0; i < newsArr.size(); i++) {
  40. Vo vo = new Vo();
  41. JSONObject jsonObject = newsArr.getJSONObject(i);
  42. vo.setId(i+1);
  43. //(信源2,阅读数xx,评论量xx)
  44. String sitename = jsonObject.getString("source_name");
  45. String read_count = jsonObject.getString("read_count");
  46. String cmt_count = jsonObject.getString("cmt_count");
  47. vo.setDesc("("+sitename+",阅读量"+read_count+",评论量"+cmt_count+")");
  48. vo.setPage_no("第"+jsonObject.getString("page_no")+"页");
  49. vo.setContent(jsonObject.getString("content"));
  50. list.add(vo);
  51. }
  52. }
  53. dataMap.put("list", list);
  54. String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
  55. String fileName = String.format("%s.docx", now);
  56. System.out.println("当前导出的word3文件---->"+dir_word3+fileName);
  57. String top_time = now.substring(0, 10).replaceAll("-", ".");
  58. dataMap.put("top_time", top_time);
  59. toWord(dataMap, dir_word3+fileName, "word3.ftl");
  60. // return dir_word3+fileName;
  61. return getBytesByFile(dir_word3+fileName);
  62. } catch (Exception e) {
  63. msg = "error";
  64. e.printStackTrace();
  65. }
  66. // return msg;
  67. return null;
  68. }
  69. @PostMapping("/downLoadWord1")
  70. public byte[] word1(@RequestBody String data){
  71. String msg = "";
  72. Map<String, Object> dataMap = new HashMap<>();
  73. List<Vo> list = new ArrayList<>();
  74. try {
  75. JSONObject json = JSONObject.parseObject(data);
  76. if(json.containsKey("news")){
  77. JSONArray newsArr = json.getJSONArray("news");
  78. for (int i = 0; i < newsArr.size(); i++) {
  79. Vo vo = new Vo();
  80. JSONObject jsonObject = newsArr.getJSONObject(i);
  81. vo.setId(i+1);
  82. String title = jsonObject.getString("title");
  83. vo.setBlogger("作者:"+jsonObject.getString("blogger"));
  84. list.add(vo);
  85. }
  86. }
  87. dataMap.put("list", list);
  88. String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
  89. String fileName = String.format("%s.docx", now);
  90. System.out.println("当前导出的word1文件---->"+dir_word1+fileName);
  91. String year = now.substring(0, 4);
  92. String month = now.substring(5, 7);
  93. String day = now.substring(8, 10);
  94. dataMap.put("year", year);
  95. dataMap.put("month", month);
  96. dataMap.put("day", day);
  97. toWord(dataMap, dir_word1+fileName, "word1.ftl");
  98. Document doc = new Document();
  99. doc.loadFromFile(dir_word1+fileName);
  100. //在文档最前面插入一个段落,写入文本并格式化
  101. Paragraph parainserted = new Paragraph(doc);
  102. doc.getSections().get(0).getParagraphs().insert(2,parainserted);
  103. parainserted.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  104. doc.getSections().get(0).getParagraphs().get(1).appendTOC(1,3);
  105. doc.updateTableOfContents();
  106. //保存文档
  107. doc.saveToFile(dir_word1+fileName, FileFormat.Docx_2010);
  108. // return dir_word1+fileName;
  109. return getBytesByFile(dir_word1+fileName);
  110. } catch (Exception e) {
  111. msg = "error";
  112. e.printStackTrace();
  113. }
  114. // return msg;
  115. return null;
  116. }
  117. public void toWord(Map<String, Object> dataMap, String docName, String ftlName) {
  118. try {
  119. //Configuration用于读取ftl文件
  120. Configuration configuration = new Configuration();
  121. configuration.setDefaultEncoding("utf-8");
  122. /*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是
  123. * 指定ftl文件所在目录的路径,而不是ftl文件的路径
  124. */
  125. //指定路径的第一种方式(根据某个类的相对路径指定)
  126. //configuration.setClassForTemplateLoading(this.getClass(),"");
  127. configuration.setClassForTemplateLoading(WordController.class, "/templates");
  128. //指定路径的第二种方式,我的路径是C:/a.ftl
  129. //configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\张胜强\\Desktop"));
  130. // 输出文档路径及名称
  131. File outFile = new File(docName);
  132. //以utf-8的编码读取ftl文件
  133. Template t = configuration.getTemplate(ftlName, "utf-8");
  134. Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
  135. t.process(dataMap, out);
  136. out.flush();
  137. out.close();
  138. } catch (Exception e) {
  139. e.printStackTrace();
  140. }
  141. }
  142. //将文件转换成Byte数组
  143. public byte[] getBytesByFile(String pathStr) {
  144. File file = new File(pathStr);
  145. System.out.println("文件大小为: " + file.length());
  146. try {
  147. FileInputStream fis = new FileInputStream(file);
  148. ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
  149. byte[] b = new byte[1024];
  150. int n;
  151. while ((n = fis.read(b)) != -1) {
  152. bos.write(b, 0, n);
  153. }
  154. fis.close();
  155. byte[] data = bos.toByteArray();
  156. bos.close();
  157. return data;
  158. } catch (Exception e) {
  159. e.printStackTrace();
  160. }
  161. return null;
  162. }
  163. }
  1. /**
  2. * 通过模板生成Excel文件
  3. * @param templateFileName 模板文件
  4. * @param fileName 目标文件
  5. * @param map 数据
  6. */
  7. public static void buildExcelByTemplate(String templateFileName, String fileName, Map map) {
  8. OutputStream outStream = null;
  9. try {
  10. outStream = new FileOutputStream(fileName);
  11. TemplateExportParams param = new TemplateExportParams(templateFileName, 0);
  12. Workbook workbook = ExcelExportUtil.exportExcel(param, map);
  13. workbook.write(outStream);
  14. } catch (IOException e) {
  15. log.error("根据模板生成Excel文件失败, 失败原因: {}", e);
  16. } finally {
  17. try {
  18. if (outStream != null) {
  19. outStream.close();
  20. }
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. }
  24. }
  25. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/article/detail/55002
推荐阅读
相关标签
  

闽ICP备14008679号