900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > java导出word表格 行列合并

java导出word表格 行列合并

时间:2018-08-30 08:35:52

相关推荐

java导出word表格 行列合并

生成word表格

新建模板如下(使用offic,不要用wps)

另存为xm格式

将文件放入resource/template目录下,复制一份,将后缀名改为ftl,也可以不复制直接改后缀名(这里忽视我其他的一些测试模板)

打开ftl文件,我们的占位符可能会错位,将他们放到一起(一定不要改动标签)

准备数据生成word

public static void main(String[] args) throws Exception {Student student1 = new Student("一年级","一班","张三","班长");Student student2 = new Student("一年级","一班","李四","班长");// Student student3 = new Student("一年级","二班","","班长");Student student4 = new Student("一年级","二班","赵六","班长");Student student5 = new Student("二年级","一班","","班长");List<Student> list = new ArrayList<>();list.add(student1);list.add(student2);// list.add(student3);list.add(student4);list.add(student5);Map<String,Object> dataMap = new HashMap<>();dataMap.put("students",list);String templateName = "student2.ftl";//这里注意一定得是doc,用doc可能会出现wps可以打开但是office打不开的情况,具体原因未知WordUtils.generateWord(dataMap, templateName, "D://demo.doc");}

对模板做如下更改

找到 w:tr 这个标签,这个标签代表表格里的行,用 <#list> 标签将其包住。<#list> 标签代表一个集合,并会循环遍历这个集合。 as l 表示给这个集合取了个别名,students就是上面主方法中map的key。

在list这个标签中用 l.xxx 这种形式就表示取当前遍历的集合元素的属性值

运行主方法,可生成如下word表格

行列合并

到这一步表格虽然生成了,但是行列合并还没有实现

下面修改模板实现行合并

列合并

修改模板行列合并后再次生成word文档效果如下

引入pom和使用util

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>

import freemarker.template.Configuration;import freemarker.template.Template;import freemarker.template.Version;import java.io.*;import java.nio.charset.StandardCharsets;import java.util.Map;/*** @author: tanghaizhi* @CreateTime: /6/27 11:38* @Description:*/public class WordUtils {/*** 生成 word 文档方法** @param dataMap要填充的数据* @param templateName 模版名称* @param fileName要输出的文件路径* @throws Exception 抛出的异常*/public static void generateWord(Map<String, Object> dataMap, String templateName, String fileName) throws Exception {// 设置FreeMarker的版本和编码格式Configuration configuration = new Configuration(new Version("2.3.28"));configuration.setDefaultEncoding("UTF-8");// 设置FreeMarker生成Word文档所需要的模板的路径// configuration.setDirectoryForTemplateLoading(new File("/Users/xxx/Desktop/"));// 此处把模版文件都放在 resources 下的 templates 中configuration.setClassForTemplateLoading(WordUtils.class, "/templates");// 设置FreeMarker生成Word文档所需要的模板Template tem = configuration.getTemplate(templateName, "UTF-8");// 创建一个Word文档的输出流Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(fileName)), StandardCharsets.UTF_8));// FreeMarker使用Word模板和数据生成Word文档tem.process(dataMap, out);out.flush();out.close();}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。