java生成word文档

java生成word文档有多种方式:java

 

  1:Jacob是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态连接库,并经过JNI的方式实现了在Java平台上对COM程序的调用。DLL动态连接库的生成须要windows平台的支持。该方案只能在windows平台实现,是其局限性。linux

 

  2:Apache POI包括一系列的API,它们能够操做基于MicroSoft OLE 2 Compound Document Format的各类格式文件,能够经过这些API在Java中读写Excel、Word等文件。他的excel处理很强大,对于word还局限于读取,目前只能实现一些简单文件的操做,不能设置样式。git

 

  3:Java2word是一个在java程序中调用 MS Office Word 文档的组件(类库)。该组件提供了一组简单的接口,以便java程序调用他的服务操做Word 文档。 这些服务包括: 打开文档、新建文档、查找文字、替换文字,插入文字、插入图片、插入表格,在书签处插入文字、插入图片、插入表格等。填充数据到表格中读取表格数据 ,1.1版加强的功能: 指定文本样式,指定表格样式。如此,则可动态排版word文档。是一种不错的解决方案。github

 

  4:iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库。经过iText不只能够生成PDF或rtf的文档,并且能够将XML、Html文件转化为PDF文件。功能强大。windows

 

  5:JSP输出样式,该方案实现简单,可是处理样式有点缺陷,简单的导出可使用。jsp

 

  6:用XML作就很简单了。Word从2003开始支持XML格式,大体的思路是先用office2003或者2007编辑好word的样式,而后另存为xml,将xml翻译为FreeMarker模板,最后用java来解析FreeMarker模板并输出Doc。经测试这样方式生成的word文档彻底符合office标准,样式、内容控制很是便利,打印也不会变形,生成的文档和office中编辑文档彻底同样。编辑器

 

 

经常使用的能够经过建立word模板,另存为 xml 格式文件替换word 文档中须要替换数据的地方,再修改后缀为 .ftl 格式的文件来操做:测试

1. 建立word文档:spa

         

 

2. 把word文档另存为 .xml 格式的文件,用office打开 .xml文件并把须要生成数据的位置用${}替换,就和jsp等页面中的EL表达式同样:翻译

      

 

3. 用编辑器打开这个 .xml格式的文件,最好是可以格式化format的编辑器,便于后面添加列表数据 ${list}:

格式化format后:

 

4. 找到须要列表的先后位置,添加接收代码,(接收列表,列表中的原参数须要略微改变,不接收列表则直接能够用key接收):

     

 

5. 修改完成后把 .xml 后缀改成 .ftl 后缀:

 

 

 

6. java测试代码:

   

 

 

7. 生成word文档以下:

 

8. java代码为:

package doword;

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.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DocUtil {
    
    /**
     * 项目文件操做地址
     */
    public static final String getfileUrl(){
        String fileUrl = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        if("acs".equals(fileUrl.substring(1,4))){
            fileUrl = (fileUrl.substring(0,fileUrl.length()-16)) + "WEB-INF/classes/file/";//阿里聚石塔
        }else if("usr".equals(fileUrl.substring(1,4))){
            fileUrl = (fileUrl.substring(0,fileUrl.length()-16)) + "WEB-INF/classes/file/";//linux
        }else{
            fileUrl = (fileUrl.substring(1,fileUrl.length()-16)) + "WEB-INF/classes/file/";//windows
        }
        return fileUrl;
    }

    /**
     * 建立word文档
     * @param dataMap 写入文档的内容
     * @param path  ftl文件所在文件夹位置(如:D:/testfile/)
     * @param fileName  ftl文件名
     * @param outPath  word文件输出文件夹位置(如:D:/testfile/)
     * @return outFilePath word文件输出地址(如:D:/testfile/xxx.doc)
     */
    public static String createWord(HashMap<String, Object> dataMap, String path, String fileName,String outPath){
        String outFileName = null;
        Template t=null;
        try {
            Configuration configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
            configuration.setDirectoryForTemplateLoading(new File(path));
            t = configuration.getTemplate(fileName); //文件名
        } catch (IOException e) {
            e.printStackTrace();
        }
        outFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString() +".doc";
        String outFilePath = outPath + outFileName;
        
        //若是文件夹不存在则建立 
        File outPathFolder = new File(outPath);
        if(!outPathFolder.exists() && !outPathFolder.isDirectory()){       
            outPathFolder.mkdir();    
        }
        
        File outFile = new File(outFilePath);
        Writer out = null;
        try {
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        try {
            t.process(dataMap, out);
            if(out != null){
                out.close();
            }
        } catch (TemplateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outFileName;
    }
    
    public static void main(String[] args) {
        HashMap<String, Object> dataMap = new HashMap<>();
        
        dataMap.put("title", "报名人员名单");
        dataMap.put("year", "2018");
        dataMap.put("month", "06");
        dataMap.put("day", "04");
        dataMap.put("createusername", "妙木山自来也");
        
        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
        for (int i = 0; i < 20; i++) {
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("username", "张三");
            map.put("age", "28");
            map.put("position", "程序猿");
            map.put("tel", "15656565656");
            list.add(map);
        }
        
        dataMap.put("list", list);
        String createWord = createWord(dataMap, "D:/testword/", "test1.ftl", "D:/testword/");
        System.out.println(createWord);
    }
    
}

9. 所需JAR包:

 

源码:https://github.com/piaoliudelaoyaoguai/testword.git

相关文章
相关标签/搜索