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

news/2024/7/21 5:25:16 标签: word, excel

需求流程:

    

模板部分如图:

Web端技术选用Jfinal

功能实现:

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

package ibasic.web.com.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import com.jfinal.kit.PropKit;

import net.sf.json.JSONObject;

//excel模板
@MultipartConfig
@WebServlet("/templateExportServlet")
public class TemplateExportServlet  extends HttpServlet{
	
	

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//		String data = req.getParameter("data");
		BufferedReader header  = req.getReader();
		StringBuffer sb = new StringBuffer();
	    String str ="" ;
        //将数据读到StringBuffer里面
	    while (null != (str = header.readLine())){
	        sb.append( str );
	    }
//	    String params = sb.toString().replaceAll("%(?![0-9a-fA-F]{2})", "%25").replaceAll("\\+", "%2B");
	
//	   String content =  URLDecoder.decode(params,"UTF-8");
		JSONObject jsonData = JSONObject.fromObject(sb.toString());
		String url = PropKit.get("template_url");
	
			RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(60000).build();
			HttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
	        HttpPost post = new HttpPost(url);
	        post.setHeader("Content-Type", "application/json");
	        String result = "";
	        
	        try {
	        
	            StringEntity s = new StringEntity(jsonData.toString(), "utf-8");
	            s.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
	            post.setEntity(s);
	            HttpResponse httpResponse = client.execute(post);
	            InputStream inStream = httpResponse.getEntity().getContent();
	           
	           
	            
	            
//	            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
//	            StringBuilder strber = new StringBuilder();
//	            String line = null;
//	            while ((line = reader.readLine()) != null){
//	                strber.append(line);
//	            }
//	            inStream.close();
//	            result = strber.toString();
//	            System.out.println(result);
	            if (HttpStatus.SC_OK != httpResponse.getStatusLine().getStatusCode()) {
	            	
	            	System.out.println("请求服务端失败"); 
	            } 
	       
	       
//	        if(!"".equals(result)){
	        	 
	        	 String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
	             String fileName = String.format("%s.xlsx", now);
	        	getFileByBytes(toByteArray(inStream), PropKit.get("excel_dir"),  fileName);
	        	download(PropKit.get("excel_dir")+fileName, resp);
//	        }
	        	
	        } catch (Exception e) {
	        	
	        	e.printStackTrace();
	        }
	}
	
	public HttpServletResponse download(String path, HttpServletResponse response) {
        try {
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
           // response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return response;
    }
	
	
	 /**
     * 将Byte数组转换成文件
     **/
    public static void getFileByBytes(byte[] bytes, String filePath, String fileName) {
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try {
            File dir = new File(filePath);
            // 判断文件目录是否存在
            if (!dir.exists() && dir.isDirectory()) {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
}

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

package com.wenge.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wenge.model.Vo;
import com.wenge.util.ExcelUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: hezha
 */
@RestController
public class ExcelControll {
    @Value("${excel.dir}")
    private String dir_path ;

    @PostMapping("/downLoadExcel")
    public  byte[] downLoadExcel(@RequestBody String data){
        String msg = "";
        Map<String, Object> dataMap = new HashMap<>();

        List<Vo> list = new ArrayList<>();

        try {
            JSONObject json = JSONObject.parseObject(data);
            if(json.containsKey("news")){
                JSONArray newsArr = json.getJSONArray("news");
                for (int i = 0; i < newsArr.size(); i++) {
                    Vo vo = new Vo();
                    JSONObject jsonObject = newsArr.getJSONObject(i);
                    vo.setId(i+1);
                    vo.setTitle(jsonObject.getString("title"));
                    list.add(vo);
                }

            }

            dataMap.put("list", list);
            String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
            String fileName = String.format("%s.xlsx", now);
            System.out.println("当前导出的excel文件---->"+dir_path+fileName);
            ExcelUtils.buildExcelByTemplate("templates/excel_template.xlsx", dir_path+fileName, dataMap);
//            return dir_path+fileName;

            return getBytesByFile(dir_path+fileName);
        } catch (Exception e) {
            msg = "error";
            e.printStackTrace();
        }
//        return msg;
        return null;
    }



    //将文件转换成Byte数组
    public byte[] getBytesByFile(String pathStr) {
        File file = new File(pathStr);
        System.out.println("文件大小为: " + file.length());
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}

 

package com.wenge.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.Section;
import com.spire.doc.collections.SectionCollection;
import com.spire.doc.documents.HorizontalAlignment;
import com.spire.doc.documents.Paragraph;
import com.wenge.model.Vo;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @description:
 * @author: hezha
 */
@RestController
public class WordController {
    @Value("${word3.dir}")
    private String dir_word3;

    @Value("${word1.dir}")
    private String dir_word1;

    @PostMapping("/downLoadWord3")
    public byte[] word3(@RequestBody String data){
        String msg = "";
        Map<String, Object> dataMap = new HashMap<>();
        List<Vo> list = new ArrayList<>();

        try {
            JSONObject json = JSONObject.parseObject(data);
            if(json.containsKey("news")){
                JSONArray newsArr = json.getJSONArray("news");
                for (int i = 0; i < newsArr.size(); i++) {
                    Vo vo = new Vo();
                    JSONObject jsonObject = newsArr.getJSONObject(i);
                    vo.setId(i+1);
                    //(信源2,阅读数xx,评论量xx)
                    String sitename = jsonObject.getString("source_name");
                    String read_count = jsonObject.getString("read_count");
                    String cmt_count  = jsonObject.getString("cmt_count");

                    vo.setDesc("("+sitename+",阅读量"+read_count+",评论量"+cmt_count+")");

                    vo.setPage_no("第"+jsonObject.getString("page_no")+"页");
                    vo.setContent(jsonObject.getString("content"));
                    list.add(vo);
                }

            }

            dataMap.put("list", list);

            String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
            String fileName = String.format("%s.docx", now);
            System.out.println("当前导出的word3文件---->"+dir_word3+fileName);

            String top_time = now.substring(0, 10).replaceAll("-", ".");
            dataMap.put("top_time", top_time);
            toWord(dataMap, dir_word3+fileName, "word3.ftl");
//            return dir_word3+fileName;
            return getBytesByFile(dir_word3+fileName);
        } catch (Exception e) {
            msg = "error";
            e.printStackTrace();
        }
//        return msg;
        return null;
    }



    @PostMapping("/downLoadWord1")
    public byte[] word1(@RequestBody String data){
        String msg = "";
        Map<String, Object> dataMap = new HashMap<>();
        List<Vo> list = new ArrayList<>();

        try {
            JSONObject json = JSONObject.parseObject(data);
            if(json.containsKey("news")){
                JSONArray newsArr = json.getJSONArray("news");
                for (int i = 0; i < newsArr.size(); i++) {
                    Vo vo = new Vo();
                    JSONObject jsonObject = newsArr.getJSONObject(i);
                    vo.setId(i+1);
                    String title = jsonObject.getString("title");
                    vo.setBlogger("作者:"+jsonObject.getString("blogger"));
                    list.add(vo);
                }

            }

            dataMap.put("list", list);

            String now = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date());
            String fileName = String.format("%s.docx", now);
            System.out.println("当前导出的word1文件---->"+dir_word1+fileName);

            String year = now.substring(0, 4);
            String month = now.substring(5, 7);
            String day = now.substring(8, 10);
            dataMap.put("year", year);
            dataMap.put("month", month);
            dataMap.put("day", day);
            toWord(dataMap, dir_word1+fileName, "word1.ftl");


            Document doc = new Document();
            doc.loadFromFile(dir_word1+fileName);


            //在文档最前面插入一个段落,写入文本并格式化
            Paragraph parainserted = new Paragraph(doc);
            doc.getSections().get(0).getParagraphs().insert(2,parainserted);
            parainserted.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
            doc.getSections().get(0).getParagraphs().get(1).appendTOC(1,3);




            doc.updateTableOfContents();
            //保存文档
            doc.saveToFile(dir_word1+fileName, FileFormat.Docx_2010);
//            return dir_word1+fileName;
            return getBytesByFile(dir_word1+fileName);
        } catch (Exception e) {
            msg = "error";
            e.printStackTrace();
        }
//        return msg;
        return null;
    }



    public  void toWord(Map<String, Object> dataMap, String docName, String ftlName) {
        try {
            //Configuration用于读取ftl文件
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("utf-8");

            /*以下是两种指定ftl文件所在目录路径的方式, 注意这两种方式都是
             * 指定ftl文件所在目录的路径,而不是ftl文件的路径
             */
            //指定路径的第一种方式(根据某个类的相对路径指定)
            //configuration.setClassForTemplateLoading(this.getClass(),"");
            configuration.setClassForTemplateLoading(WordController.class, "/templates");

            //指定路径的第二种方式,我的路径是C:/a.ftl
            //configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\张胜强\\Desktop"));

            // 输出文档路径及名称
            File outFile = new File(docName);

            //以utf-8的编码读取ftl文件
            Template t = configuration.getTemplate(ftlName, "utf-8");
            Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "utf-8"), 10240);
            t.process(dataMap, out);
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //将文件转换成Byte数组
    public byte[] getBytesByFile(String pathStr) {
        File file = new File(pathStr);
        System.out.println("文件大小为: " + file.length());
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            byte[] data = bos.toByteArray();
            bos.close();
            return data;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
/**
     * 通过模板生成Excel文件
     * @param templateFileName 模板文件
     * @param fileName 目标文件
     * @param map 数据
     */
    public static void buildExcelByTemplate(String templateFileName, String fileName, Map map) {
        OutputStream outStream = null;
        try {
            outStream = new FileOutputStream(fileName);
            TemplateExportParams param = new TemplateExportParams(templateFileName, 0);
            Workbook workbook = ExcelExportUtil.exportExcel(param, map);
            workbook.write(outStream);
        } catch (IOException e) {
            log.error("根据模板生成Excel文件失败, 失败原因: {}", e);
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


http://www.niftyadmin.cn/n/5352984.html

相关文章

【Spring连载】使用Spring访问 Apache Kafka(二十)----测试应用

【Spring连载】使用Spring访问 Apache Kafka&#xff08;二十&#xff09;----测试应用Testing Applications 一、KafkaTestUtils二、JUnit三、配置主题Configuring Topics四、为多个测试类使用相同的broker&#xff0c;Using the Same Broker(s) for Multiple Test Classes五、…

大数据 - Hadoop系列《三》- MapReduce(分布式计算引擎)概述

上一篇文章&#xff1a; 大数据 - Hadoop系列《三》- HDFS&#xff08;分布式文件系统&#xff09;概述-CSDN博客 目录 12.1 针对MapReduce的设计构思 1. 如何对付大数据处理场景 2. 构建抽象编程模型 3. 统一架构、隐藏底层细节 12.2 分布式计算概念 12.3 MapReduce定义…

分布式ID是什么,以美团Leaf为例改造融入自己项目【第十一期】

前言 在日常开发中&#xff0c;主键id应用是非常广泛的&#xff0c;但是当涉及到分布式系统的时候&#xff0c;往往需要使用到分布式id&#xff0c;每一个服务里面一套生成规则的不易管理&#xff0c;容易引发冲突。我的IM聊天系统中使用分布式id来生成消息唯一键,为后面幂等做…

4D毫米波雷达——ADCNet 原始雷达数据 目标检测与可行驶区域分割

前言 本文介绍使用4D毫米波雷达&#xff0c;基于原始雷达数据&#xff0c;实现目标检测与可行驶区域分割&#xff0c;它是来自2023-12的论文。 会讲解论文整体思路、输入分析、模型框架、设计理念、损失函数等&#xff0c;还有结合代码进行分析。 论文地址&#xff1a;ADCNe…

【Vue】2-3、Vue 的基本使用

一、基本使用步骤 导入 vue.js 的 script 脚本文件 在页面中声明一个将要被 vue 所控制的区域 创建 vm 实例对象&#xff08;vue 实例对象&#xff09; 这里需要先在官网下载 vue.js 文件 <body><div id"app"> {{ username }} </div><!-- 导…

借助gpt生成ppt:文心一言(chatgpt)、chatppt

提供一种简单的基于gpt快速生成ppt的方式。前置条件&#xff1a; 文心一言chatpptwps/office ppt Step1: 下载chatppt插件 https://chat-ppt.com/invitelinke?share_code47949695&channelchat-ppt.com 注册地址 下载完成后&#xff0c;安装即可&#xff0c;安装完成后…

nrm-npm包版本管理和详细安装和使用教程

1&#xff09;nrm 是什么&#xff1f; nrm是一个npm源管理器&#xff0c;它允许用户快速地在不同的npm源之间切换。项目中使用nrm&#xff0c;可以加快npm包的下载速度&#xff0c;切换不同的npm源。平时在用 npm i 或 yarn 安装 npm 包的时候&#xff0c;可能会感觉下载比较慢…

R语言【taxlist】——tax2traits():将分类信息设置为分类单元特征

Package taxlist version 0.2.4 Description 分类法分类可以包含在taxonRelations插槽提供的信息中的 taxlist 对象中。然而&#xff0c;对于统计分析来说&#xff0c;将这些信息插入到插槽taxonTraits中可能更方便。 Usage tax2traits(object, ...)## S3 method for class …