利用模板匯出檔案(二)之jacob利用word模板匯出word檔案(Java2word)
先下載jacob.jar包。解壓後將jacob.dll放到windows/system32下面或\jre\bin下面。將jacob.jar加入專案。
這樣專案的環境基本上搭建完成,接下來就是書寫相關的程式碼:
/**
* 傳入資料為HashMap物件,物件中的Key代表word模板中要替換的欄位,Value代表用來替換的值。
* word模板中所有要替換的欄位(即HashMap中的Key)以特殊字元開頭和結尾,
* 如:$code$、$date$……,以免執行錯誤的替換。
* 所有要替換為圖片的欄位,Key中需包含image或者Value為圖片的全路徑
* (目前只判斷檔案字尾名為:.bmp、.jpg、.gif)。
* 要替換表格中的資料時,HashMap中的Key格式為“ [email protected]”,其中:
* R代表從表格的第R行開始替換,N代表word模板中的第N張表格;
* Value為ArrayList物件,ArrayList中包含的物件統一為String[],一條String[]代表一行資料,
* ArrayList中第一條記錄為特殊記錄,記錄的是表格中要替換的列號,
* 如:要替換第一列、第二列、第三列的資料,則第一條記錄為String[3] {"1","2","3"}。
*/
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
* 利用word模板生成word檔案
* @typename:Java2word
* @author: FishRoad
* @since: 2015年8月24日 下午2:47:41
*
*/
public class Java2word {
private boolean saveOnExit;
/**
* word文件
*/
Dispatch doc = null;
/**
* word執行程式物件s
*/
private ActiveXComponent word;
/**
* 所有word文件
*/
private Dispatch documents;
/**
* 建構函式
*/
public Java2word() {
if(word==null){
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible",new Variant(false));
}
if(documents==null)
documents = word.getProperty("Documents").toDispatch();
saveOnExit = false;
}
/**
* 設定引數:退出時是否儲存
* @param saveOnExit boolean true-退出時儲存檔案,false-退出時不儲存檔案
*/
public void setSaveOnExit(boolean saveOnExit) {
this.saveOnExit = saveOnExit;
}
/**
* 得到引數:退出時是否儲存
* @return boolean true-退出時儲存檔案,false-退出時不儲存檔案
*/
public boolean getSaveOnExit() {
return saveOnExit;
}
/**
* 開啟檔案
* @param inputDoc String 要開啟的檔案,全路徑
* @return Dispatch 開啟的檔案
*/
public Dispatch open(String inputDoc) {
return Dispatch.call(documents,"Open",inputDoc).toDispatch();
}
/**
* 選定內容
* @return Dispatch 選定的範圍或插入點
*/
public Dispatch select() {
return word.getProperty("Selection").toDispatch();
}
/**
* 把選定內容或插入點向上移動
* @param selection Dispatch 要移動的內容
* @param count int 移動的距離
*/
public void moveUp(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveUp");
}
/**
* 把選定內容或插入點向下移動
* @param selection Dispatch 要移動的內容
* @param count int 移動的距離
*/
public void moveDown(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveDown");
}
/**
* 把選定內容或插入點向左移動
* @param selection Dispatch 要移動的內容
* @param count int 移動的距離
*/
public void moveLeft(Dispatch selection,int count) {
for(int i = 0;i < count;i ++) {
Dispatch.call(selection,"MoveLeft");
}
}
/**
* 把選定內容或插入點向右移動
* @param selection Dispatch 要移動的內容
* @param count int 移動的距離
*/
public void moveRight(Dispatch selection,int count) {
for(int i = 0;i < count;i ++)
Dispatch.call(selection,"MoveRight");
}
/**
* 把插入點移動到檔案首位置
* @param selection Dispatch 插入點
*/
public void moveStart(Dispatch selection) {
Dispatch.call(selection,"HomeKey",new Variant(6));
}
/**
* 從選定內容或插入點開始查詢文字
* @param selection Dispatch 選定內容
* @param toFindText String 要查詢的文字
* @return boolean true-查詢到並選中該文字,false-未查詢到文字
*/
public boolean find(Dispatch selection,String toFindText) {
//從selection所在位置開始查詢
Dispatch find = word.call(selection,"Find").toDispatch();
//設定要查詢的內容
Dispatch.put(find,"Text",toFindText);
//向前查詢
Dispatch.put(find,"Forward","True");
//設定格式
Dispatch.put(find,"Format","True");
//大小寫匹配
Dispatch.put(find,"MatchCase","True");
//全字匹配
Dispatch.put(find,"MatchWholeWord","True");
//查詢並選中
return Dispatch.call(find,"Execute").getBoolean();
}
/**
* 把選定內容替換為設定文字
* @param selection Dispatch 選定內容
* @param newText String 替換為文字
*/
public void replace(Dispatch selection,String newText) {
//設定替換文字
Dispatch.put(selection,"Text",newText);
}
/**
* 全域性替換
* @param selection Dispatch 選定內容或起始插入點
* @param oldText String 要替換的文字
* @param newText String 替換為文字
*/
public void replaceAll(Dispatch selection,String oldText,Object replaceObj) {
//移動到檔案開頭
moveStart(selection);
if(oldText.startsWith("table") || replaceObj instanceof ArrayList)
replaceTable(selection,oldText,(ArrayList) replaceObj);
else {
String newText = (String) replaceObj;
if(newText==null)
newText="";
if(oldText.indexOf("image") != -1&!newText.trim().equals("") || newText.lastIndexOf(".bmp") != -1 || newText.lastIndexOf(".jpg") != -1 || newText.lastIndexOf(".gif") != -1){
while(find(selection,oldText)) {
replaceImage(selection,newText);
Dispatch.call(selection,"MoveRight");
}
}else{
while(find(selection,oldText)) {
replace(selection,newText);
Dispatch.call(selection,"MoveRight");
}
}
}
}
/**
* 替換圖片
* @param selection Dispatch 圖片的插入點
* @param imagePath String 圖片檔案(全路徑)
*/
public void replaceImage(Dispatch selection,String imagePath) {
Dispatch.call(Dispatch.get(selection,"InLineShapes").toDispatch(),"AddPicture",imagePath);
}
/**
* 替換表格
* @param selection Dispatch 插入點
* @param tableName String 表格名稱,
* 形如 [email protected]、[email protected][email protected],R代表從表格中的第N行開始填充,N代表word檔案中的第N張表
* @param fields HashMap 表格中要替換的欄位與資料的對應表
*/
public void replaceTable(Dispatch selection,String tableName,ArrayList dataList) {
if(dataList.size() <= 1) {
System.out.println("Empty table!");
return;
}
//要填充的列
String[] cols = (String[]) dataList.get(0);
//表格序號
String tbIndex = tableName.substring(tableName.lastIndexOf("@") + 1);
//從第幾行開始填充
int fromRow = Integer.parseInt(tableName.substring(tableName.lastIndexOf("$") + 1,tableName.lastIndexOf("@")));
//所有表格
Dispatch tables = Dispatch.get(doc,"Tables").toDispatch();
//要填充的表格
Dispatch table = Dispatch.call(tables,"Item",new Variant(tbIndex)).toDispatch();
//表格的所有行
Dispatch rows = Dispatch.get(table,"Rows").toDispatch();
//填充表格
for(int i = 1;i < dataList.size();i ++) {
//某一行資料
String[] datas = (String[]) dataList.get(i);
//在表格中新增一行
if(Dispatch.get(rows,"Count").getInt() < fromRow + i - 1)
Dispatch.call(rows,"Add");
//填充該行的相關列
for(int j = 0;j < datas.length;j ++) {
//得到單元格
Dispatch cell = Dispatch.call(table,"Cell",Integer.toString(fromRow + i - 1),cols[j]).toDispatch();
//選中單元格
Dispatch.call(cell,"Select");
//設定格式
Dispatch font = Dispatch.get(selection,"Font").toDispatch();
Dispatch.put(font,"Bold","0");
Dispatch.put(font,"Italic","0");
//輸入資料
Dispatch.put(selection,"Text",datas[j]);
}
}
}
/**
* 儲存檔案
* @param outputPath String 輸出檔案(包含路徑)
*/
public void save(String outputPath) {
Dispatch.call(Dispatch.call(word,"WordBasic").getDispatch(),"FileSaveAs",outputPath);
}
/**
* 關閉檔案
* @param document Dispatch 要關閉的檔案
*/
public void close(Dispatch doc) {
Dispatch.call(doc,"Close",new Variant(saveOnExit));
word.invoke("Quit",new Variant[]{});
word = null;
}
/**
* 根據模板、資料生成word檔案
* @param inputPath String 模板檔案(包含路徑)
* @param outPath String 輸出檔案(包含路徑)
* @param data HashMap 資料包(包含要填充的欄位、對應的資料)
*/
public void toWord(String inputPath,String outPath,HashMap data) {
String oldText;
Object newValue;
try {
if(doc==null)
doc = open(inputPath);
Dispatch selection = select();
Iterator keys = data.keySet().iterator();
while(keys.hasNext()) {
oldText = (String) keys.next();
newValue = data.get(oldText);
replaceAll(selection,oldText,newValue);
}
save(outPath);
} catch(Exception e) {
System.out.println("操作word檔案失敗!");
e.printStackTrace();
} finally {
if(doc != null)
close(doc);
}
}
public synchronized static void word(String inputPath,String outPath,HashMap data){
Java2word j2w = new Java2word();
j2w.toWord(inputPath,outPath,data);
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
//替換word中相關的欄位
HashMap data = new HashMap();
data.put("$reportDept$","2007-8-1");
data.put("$findDate$","2007-8-2");
data.put("$finder$","kdl");
data.put("$lineName$","5號線");
data.put("$voltageRate$","11月13日");
data.put("$towerNumberBound$","2004年11月10日");
data.put("$image1$","C:\\Users\\Administrator\\Pictures\\1.jpg");
data.put("$name$", "FishRoad");
data.put("$age$", "24");
//替換word中表格的資料
/**
* 要替換表格中的資料時,HashMap中的Key格式為“ [email protected]”,其中:
* R代表從表格的第R行開始替換,N代表word模板中的第N張表格;
* Value為ArrayList物件,ArrayList中包含的物件統一為String[],
* 一條String[]代表一行資料,ArrayList中第一條記錄為特殊記錄,記錄的是表格中要替換的列號,
* 如:要替換第一列、第二列、第三列的資料,則第一條記錄為String[3] {"1","2","3"}
*/
ArrayList table1 = new ArrayList(3);
String[] fieldName1 = {"1","2","3"};
table1.add(fieldName1);
String[] field11 = {"1","751002","華夏證券"};
table1.add(field11);
String[] field21 = {"2","751004","國泰君安"};
table1.add(field21);
String[] field31 = {"3","751005","海通證券"};
table1.add(field31);
data.put("[email protected]",table1);
Java2word j2w = new Java2word();
long time1 = System.currentTimeMillis();
j2w.toWord("E:/template.doc","E:/result.doc",data);
System.out.println("time cost : " + (System.currentTimeMillis() - time1));
}
}
以上是相關的程式碼,接下來就要配置word模板,如下:
匯出的結果如下圖:
相關推薦
利用模板匯出檔案(二)之jacob利用word模板匯出word檔案(Java2word)
先下載jacob.jar包。解壓後將jacob.dll放到windows/system32下面或\jre\bin下面。將jacob.jar加入專案。 這樣專案的環境基本上搭建完成,接下來就是書寫相關的程式碼: /** * 傳入資料為HashMap物件,物件中的Key代表w
精盡MyBatis原始碼分析 - MyBatis初始化(二)之載入 Mapper 介面與 XML 對映檔案
> 該系列文件是本人在學習 Mybatis 的原始碼過程中總結下來的,可能對讀者不太友好,請結合我的原始碼註釋([Mybatis原始碼分析 GitHub 地址](https://github.com/liu844869663/mybatis-3)、[Mybatis-Spring 原始碼分析 GitHub 地址
MySQL(九)之數據表的查詢詳解(SELECT語法)二
clas reg 3.2 查詢語句 我們 lin where 過濾 情況 上一篇講了比較簡單的單表查詢以及MySQL的組函數,這一篇給大家分享一點比較難得知識了,關於多表查詢,子查詢,左連接,外連接等等。希望大家能都得到幫助! 在開始之前因為要多表查詢,所以搭建好環境:
計算機網路實驗(二)之Wireshark抓包分析獲取URL列表(去重、排序、統計)
實驗要求 本試驗要求基於第一次實驗中訪問某官網主頁時所抓取到的資料包,用Python 3語言、Jupyter Notebook和Pyshark編寫程式碼進行協議分析所需的開發環境,編寫程式碼,以輸出的方式列出首頁以及其所包含的所有資源(至少包含如下型別
軟體開發過程學習筆記(三)之概要設計說明書模板
1 引言 本設計書主要是基於以下目的編寫: 1、對系統概要設計的階段任務成果形成文件,以便階段驗收、評審,最終的文件驗收。 2、對需求階段的文件再次確認過程,對前一階段需求沒有做充分或錯誤的提出修改。 3、明確整個系統的功能框架和資料庫結構,為下一階段的詳細設計、編碼、和
Binary Tree Level Order Traversal(二叉樹層序遍歷-儲存並返回結果集)
題目描述 Given a binary tree, return the level order traversal of its nodes’ values. (ie, from left to right, level by level). For example: Given
《Python學習手冊》學習筆記(4)之第4章介紹Python物件型別(關鍵詞:程式語言/Python)
第4章 介紹Python物件型別 寫在開頭的讀者筆記 值得一讀的小節 1.“為什麼使用內建型別” - “Python的核心資料型別”,主要學到了: Python是強型別語言,你只能對一個物件進行適合該型別的有效操作。 一旦建立了一個物件,它就和
POJ 2155 Matrix(二維樹狀陣列+陣列陣列區間更新+單點查詢)
Given an N*N matrix A, whose elements are either 0 or 1. A[i, j] means the number in the i-th row and j-th column. Initially we have A[
SparkCore運算元(例項)之---- 交集、差集、並集(intersection, subtract, union, distinct, subtractByKey)
1. 交集 intersecion 1.1 原始碼 /** * Return the intersection of this RDD and another one. The output will not contain any duplicate
(轉)JavaWeb學習之Servlet(二)----Servlet的生命周期、繼承結構、修改Servlet模板
ext 核心 system 網頁 基本 麻煩 extends 用戶名 servlet對象 【聲明】 歡迎轉載,但請保留文章原始出處→_→ 文章來源:http://www.cnblogs.com/smyhvae/p/4140466.html 一、http協議回顧: 在上一
Spring整合Struts2和Hibernate+Maven(二)之SSH的配置檔案
上次講到的是maven專案的建立以及pom.xml的配置。 這裡推薦一個網站:maven整合jar包,這裡可以查詢並生成配置檔案中jar包匯入格式的文字,複製貼上到pom.xml中即可由idea自動下載並匯入專案。 resources資料夾 建立ssh的配置檔案至上章圖片中的res
Meteor學習路程(二)之模板的例子
首先先介紹Meteor模板系統Spacebars: Spachebars只是在HTML基礎上多個標籤,Meteor只是讓模板和邏輯進行分離。為了讓連線變得更加流暢,一個模板需要helper(helper就是廚師用的食材(資料),烹飪好佳餚(模板),再由伺服器端到你面前),換另一種說法就是(模
node總結之檔案操作系列(二)
接著上一篇部落格來啊,咱們繼續看非同步模式下關閉檔案的語法格式: fs.close(fd, callback) 引數描述如下: fd - 通過 fs.open() 方法返回的檔案描述符。 callback - 回撥函式,沒有引數。 例項如下: var
C語言入門(廿二)之預處理指令、巨集、條件編譯、檔案包含、typedef、const
預處理指令 什麼是預處理指令: 在我們的檔案翻譯成0和1之前做的操作我們稱之為預處理指令。一般情況預處理指令都是以#號開頭的。 巨集定義的格式 不帶引數的巨集定義: #define 巨集名 值 巨集定義的作用:
2018 - Python 3.7 爬蟲之 利用 Scrapy 框架 獲取圖片並下載(二)
一、 通過命令構建一個爬蟲專案 二、定義 item 三、啟用 pipeline 管道 四、編寫爬蟲 Spider 五、執行爬蟲 六、結果檢視 未安裝 Scrapy 框架,見上一篇文章:框架安裝及配置 一、 通過命令構建一個爬蟲專
Django框架(二)—— 基本配置:app註冊、模板配置、靜態檔案配置、資料庫連線配置post和get
app註冊、模板配置、靜態檔案配置、資料庫連線配置post和get 一、app 在Django中,APP可以用以下類比 大學 --------------------專案 計算機學院------------app01 土木學院 ------------ app02 1、app建立 方
前端開發框架總結之利用Jtopo實現網路拓撲功能(二)
前端開發框架總結之利用Jtopo實現網路拓撲功能(二) 上文我們講了一些拓撲結點生成的實際場景設計和實現思路以及一些關鍵技術細節。本文我們繼續我們的拓撲管理
git 學習(散記)之二(檔案提交、版本回退、暫存區與工作區、撤銷修改)
提示:如果是初學者 可以按照我的命令敲一遍。在第一篇要去註冊一個github賬號才能繫結本地倉庫 一、修改檔案處理以及檢視操作 vim readme.txt //開啟後隨便修改一下 git status //檢視狀態
linux一切皆檔案之Unix domain socket描述符(二)
一、知識準備 1、在linux中,一切皆為檔案,所有不同種類的型別都被抽象成檔案(比如:塊裝置,socket套接字,pipe佇列) 2、操作這些不同的型別就像操作檔案一樣,比如增刪改查等 3、主要用於:執行在同一臺機器上的2個程序相互之間的資料通訊 4、它們和網路檔案描述符非常相似(比如:TCP
【Android架構】基於MVP模式的Retrofit2+RXjava封裝之檔案下載(二)
上篇中我們介紹了基於MVP的Retrofit2+RXjava封裝,還沒有看的點選這裡,這一篇我們來說說檔案下載的實現。 首先,我們先在ApiServer定義好呼叫的介面 @GET Observable<ResponseBody> downloadFile(@