按照模板生成文件,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();
            }
        }
    }

  • 8
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 将Excel中的数据按照Word模板生成Word文档可以通过使用宏代码或者使用Python等编程语言来实现。 使用宏代码的方法是,首先打开ExcelWord软件,然后在Excel中选择需要导出到Word的数据范围,点击开发工具栏中的"视图代码"按钮,将打开宏编辑器。在宏编辑器中,编写代码来读取Excel中的数据,并将数据插入到Word模板中的相应位置。最后保存并运行该宏,即可生成Word文档。 另一种方法是使用Python等编程语言来实现,首先需要安装相应的库文件,如openpyxl和python-docx。然后在Python中编写代码,使用openpyxl库读取Excel中的数据,并使用python-docx库创建Word文档并将数据插入到文档中的相应位置。最后保存生成Word文档。 无论是使用宏代码还是编程语言,都需要明确Excel中数据的格式和Word模板的格式,并保存好模板文件。在生成Word文档时,需要注意将数据插入到正确的位置,保持格式的一致性。通过这种方法,可以简化手动复制粘贴的过程,提高生成文档的效率,并确保数据的准确性。 ### 回答2: 将Excel中的数据按照Word模板生成Word文档可以通过使用VBA宏来实现。下面是具体的操作步骤: 1. 打开Excel文件并选择需要导入到Word中的数据。 2. 创建一个新的Word文档,并在文档中插入一个表格或者其他需要插入数据的位置。 3. 在Excel中,按下“ALT+F11”打开VBA编辑器。 4. 在VBA编辑器中,点击菜单栏中的“插入”,选择“模块”,添加一个新的模块。 5. 在新建的模块中编写VBA宏代码来实现将Excel数据导入到Word中的功能。可以使用Excel的对象模型来获取数据,使用Word的对象模型来进行文档的创建和修改。具体的代码可以查看相关的VBA编程教程和参考资料。 6. 完成VBA宏代码编写后,保存并关闭VBA编辑器。 7. 在Excel中选中需要导入的数据,运行刚刚编写的VBA宏。 8. VBA宏会自动将选中的数据按照Word模板生成Word文档,保存在指定的路径下。 需要注意的是,需要提前准备好Word模板,并确保模板中的表格或其他需要导入数据的位置与VBA宏中的代码一致。另外,VBA宏中还可以进行格式化和样式设置等操作,以满足生成Word文档的需求。 ### 回答3: 将Excel中的数据按照Word模板生成Word文档可以通过编写代码来实现。 首先,需要使用编程语言(比如Python)来进行开发。一个常用的工具是使用Python中的openpyxl库来读取Excel文件中的数据。可以逐行读取数据,并将其存储到相应的变量中。 接下来,需要使用Python中的python-docx库来操作Word文档。可以先打开Word模板文件,然后通过指定的关键字(比如占位符)来定位需要填充数据的位置。 然后,将从Excel中读取到的数据逐个填充到Word模板中的相应位置。可以使用python-docx提供的功能,比如paragraphs和tables,来插入表格、段落或文字。 最后,保存生成Word文档文件。 这个过程中,可以添加一些附加的处理,比如格式化文本、插入图片等,以满足具体的需求。 总之,借助合适的编程语言和相关库的帮助,我们可以将Excel中的数据按照Word模板的格式生成Word文档。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值