用java SWT操作word 進行修改
package com.ui.input;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import org.eclipse.swt.widgets.DateTime;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
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.invoke(documents,"Open",Dispatch.Method,new Object[]{inputDoc},new int[1]).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 表格名稱,形如table$1@1、table$2@1...table$R@N,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);
}
public static long Input(String name,String qq,String pwd,String oaname) {
HashMap data = new HashMap();
data.put("$a$",name);
data.put("$b$",qq);
data.put("$c$",pwd);
data.put("$d$",oaname);
Java2Word j2w = new Java2Word();
long time1 = System.currentTimeMillis();
j2w.toWord("D:\\doc\\tax\\新員工入司需知.doc","D:\\新員工入司需知.doc",data);
return (System.currentTimeMillis() - time1);
}
}
--------------------------------------------分割線---------------------------------------------------
//測試類。沒有全調用Java2Word的方法。。太麻煩- -
package com.ui.input;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import com.sun.xml.internal.ws.api.message.Message;
import org.eclipse.wb.swt.SWTResourceManager;
public class Test {
protected Shell shell;
private Label lblNewLabel;
private Label lblqq;
private Label lblOa;
private Label label_2;
private Label lblQq;
private Text textname;
private Text textqq;
private Text textpwd;
private Text textoa;
private Button btnNewButton;
private Button btnNewButton_1;
private Button button;
/**
* Launch the application.
*
* @param args
*/
public static void main(String[] args) {
try {
Test window = new Test();
window.open();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Open the window.
*/
public void open() {
Display display = Display.getDefault();
createContents();
shell.open();
shell.layout();
while (!shell.isDisposed()) {
if (!display.readAndDispatch()) {
display.sleep();
}
}
}
/**
* Create contents of the window.
*/
protected void createContents() {
shell = new Shell();
shell = new Shell(SWT.CLOSE);//實例化窗體只有關閉按鈕
shell = new Shell(SWT.MIN | SWT.CLOSE);//實例化窗體 不允許改變大小
shell.setImage(SWTResourceManager.getImage(Test.class, "/images/RF.png"));
//shell.setImage(SWTResourceManager.getImage("..\\images\\RF.png"));
shell.setSize(443, 295);
shell.setText("\u65B0\u5458\u5DE5\u5165\u804C\u901A\u77E5\u5355");
lblNewLabel = new Label(shell, SWT.NONE);
lblNewLabel.setBounds(57, 43, 54, 12);
lblNewLabel.setText("\u5458\u5DE5\u59D3\u540D\uFF1A");
lblqq = new Label(shell, SWT.NONE);
lblqq.setText("\u5458\u5DE5QQ\uFF1A");
lblqq.setBounds(57, 77, 54, 12);
lblOa = new Label(shell, SWT.NONE);
lblOa.setText("OA\u8D26\u53F7\uFF1A");
lblOa.setBounds(57, 143, 54, 12);
label_2 = new Label(shell, SWT.NONE);
label_2.setText("\u5458\u5DE5\u59D3\u540D\uFF1A");
label_2.setBounds(44, 129, 54, -11);
lblQq = new Label(shell, SWT.NONE);
lblQq.setText("QQ\u5BC6\u7801\uFF1A");
lblQq.setBounds(57, 103, 54, 12);
textname = new Text(shell, SWT.BORDER);
textname.setBounds(144, 40, 141, 18);
textqq = new Text(shell, SWT.BORDER);
textqq.setBounds(144, 74, 141, 18);
textpwd = new Text(shell, SWT.BORDER);
textpwd.setBounds(144, 100, 141, 18);
textoa = new Text(shell, SWT.BORDER);
textoa.setBounds(144, 140, 141, 18);
btnNewButton = new Button(shell, SWT.NONE);
btnNewButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Java2Word jWord = new Java2Word();
String name = textname.getText();
String qq = textqq.getText();
String pwd = textpwd.getText();
String oaname = textoa.getText();
long lg = jWord.Input(name, qq, pwd, oaname);
if (lg==0) {
MessageBox messageBox = new MessageBox(shell, SWT.ERROR
| SWT.YES | SWT.OK);
messageBox.setMessage("添加失敗!");
messageBox.setText("提示");
messageBox.open();
}else{
MessageBox messageBox = new MessageBox(shell, SWT.ICON_INFORMATION);
messageBox.setMessage("添加成功!");
messageBox.setText("提示");
messageBox.open();
}
}
});
btnNewButton.setBounds(90, 199, 72, 22);
btnNewButton.setText("\u786E\u5B9A");
btnNewButton_1 = new Button(shell, SWT.NONE);
btnNewButton_1.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
textname.setText("");
textoa.setText("");
textpwd.setText("");
textqq.setText("");
}
});
btnNewButton_1.setBounds(298, 199, 72, 22);
btnNewButton_1.setText("\u91CD\u7F6E");
button = new Button(shell, SWT.NONE);
button.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
shell.close();
}
});
button.setText("\u5173\u95ED");
button.setBounds(192, 199, 72, 22);
}
}