使用freemarker测试生成word文档

导入jar包

freemarker使用需要导入jar包

编辑word模板

简单示例:
在这里插入图片描述

word模板另存为.xml

在这里插入图片描述

修改后缀名为.ftl

本人使用eclipse打开ftl文件,文件格式直观些,需设置使用jsp格式打开ftl文件,百度即可
找到需要循环的表格内容,加上
<#list userList as list></#list>
单元格的内容修改为设置的对应的 对象.属性
在这里插入图片描述

java代码

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import freemarker.core.ParseException;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class FreemarkerTest {
private Configuration configuration = null;

public FreemarkerTest() {
	configuration = new Configuration();
	configuration.setDefaultEncoding("UTF-8");
}
public void createWord() throws ParseException, IOException{
	
	Map<String, Object> dataMap = new HashMap<>();
	getData(dataMap);
	//configuration.setClassForTemplateLoading(this.getClass(), "C:\\Users\\Admin\\Desktop");//模板文件所在路径
	configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\Admin\\Desktop\\freemarker"));
	Template t=null;  
	try {  
         t = configuration.getTemplate("word.ftl","utf-8"); //获取模板文件
     } catch (IOException e) {  
         e.printStackTrace();  
     }  
     File outFile = new File("C:\\Users\\Admin\\Desktop\\freemarker\\outFile.doc"); //导出文件
     Writer out = null;  
    try {  
         out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));  
     } catch (FileNotFoundException e1) {  
        e1.printStackTrace();  
     }  
        
     try {  
         t.process(dataMap, out); //将填充数据填入模板文件并输出到目标文件 
     } catch (TemplateException e) {  
         e.printStackTrace();  
     } catch (IOException e) {  
         e.printStackTrace();  
     }  
}
 private void getData(Map<String, Object> dataMap) throws ParseException {  
	//操作人
	dataMap.put("userName", "张三");
	//日期
	dataMap.put("createTime", new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()));
    
	List<Map<String, Object>> list=new ArrayList<Map<String,Object>>();
	
	for(int i=0;i<10;i++){
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("name", "张三"+i);
		map.put("age", (i*2));
		map.put("phone","1122334455");
		list.add(map);
	}
	dataMap.put("userList", list);
      
   
 } 

public static void main(String[] args) throws ParseException, IOException {
	FreemarkerTest test = new FreemarkerTest();
	test.createWord();
}

}

在遇到导出word需求时,曾看过一篇类似的文章,自己闲来无事,做个类似的demo,希望下次遇到直接拿过来使用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
您好!对于Spring Boot使用Freemarker模板生成Word文档并加密的例子,可以按照以下步骤进行操作: 1. 首先,您需要在pom.xml文件中添加Freemarker和Apache POI的依赖项。在 `<dependencies>` 标签内添加以下代码: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>4.1.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>4.1.2</version> </dependency> ``` 2. 创建一个Freemarker模板文件,例如 `template.ftl`,并在其中编写Word文档的内容,可以使用Freemarker语法进行动态内容替换。 3. 创建一个Controller类,并添加以下代码: ```java import freemarker.template.Configuration; import freemarker.template.Template; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFEncryptor; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import javax.servlet.http.HttpServletResponse; import java.io.OutputStream; import java.util.HashMap; import java.util.Map; @Controller public class WordController { @Autowired private Configuration freemarkerConfiguration; @GetMapping("/generate-word") public void generateWord(HttpServletResponse response) throws Exception { // 加载Freemarker模板 Template template = freemarkerConfiguration.getTemplate("template.ftl"); // 创建Word文档对象 XWPFDocument document = new XWPFDocument(); // 创建段落对象 XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); // 填充模板内容 Map<String, Object> data = new HashMap<>(); // 添加模板中需要的数据,可以根据实际需求自行修改 // 渲染模板 run.setText(templateToString(template, data)); // 加密Word文档 XWPFEncryptor encryptor = new XWPFEncryptor(document); encryptor.encrypt("password"); // 替换为您自己的密码 // 设置响应头 response.setHeader("Content-disposition", "attachment; filename=encrypted_word.docx"); response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // 导出Word文档 OutputStream outputStream = response.getOutputStream(); document.write(outputStream); outputStream.close(); } private String templateToString(Template template, Map<String, Object> data) throws Exception { StringWriter stringWriter = new StringWriter(); template.process(data, stringWriter); return stringWriter.toString(); } } ``` 4. 在Spring Boot的配置文件(例如 `application.properties`)中添加以下配置: ```properties spring.freemarker.template-loader-path=classpath:/templates/ ``` 5. 运行Spring Boot应用程序,并访问 `/generate-word` 路径,即可生成并下载加密的Word文档。 请注意,上述代码仅为示例,您可以根据实际需求进行修改和扩展。同时,为了确保文档的安全性,请根据您的需求修改加密密码和文件名。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值