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

相關文章
相關標籤/搜索