JAva操作word

14662 ワード

ここ数日、java操作wordドキュメントという問題に遭遇したばかりです.
まずjarパッケージのサポートをダウンロードする必要があります.個人的にはjacob 1.9.jarを使用しています.
よく見るとjava操作wordフォーマットが固定されていることがわかります.
私が実現したい機能は、テンプレートに基づいてwordをコピーし、その中のタグ文字を後で変更する文字に置き換えることです.機能の基本的な実装
 
 
1新しいjavaプロジェクトインポートjarパッケージ
2workMarker.java
package jacob;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class WordMaker {

	Map<String, String> info;
	private String textPath;
	private static String outWord;
	protected ActiveXComponent word;
	protected Dispatch documents;
	protected Dispatch document;
	private Dispatch selection;

	protected Dispatch range;
	protected Dispatch find;
	protected Dispatch paragraphs;
	protected Dispatch tables;
	public static final int wdFindContinue = 1;
	
	public WordMaker() {
		super();
	}

	/**
	 *       word 
	 * @param textPath        
	 * @param outWord          
	 * @param info       Map<String,String>  key       value      
	 */
	public void buildWord(String textPath, String outWord, Map<String, String> info) {
		 
		
		if (textPath != null && new File(textPath).exists()) {
			this.info = info;
			this.textPath = textPath;
			this.outWord = outWord;
			initFields();
		}
	}
 
	/**
	 *    jacob     Dispatch    
	 * 
	 */
	protected void initFields() {
		try {
			this.word = new ActiveXComponent("Word.Application"); //
			this.word.setProperty("Visible", new Variant(false));

			this.documents = this.word.getProperty("Documents").toDispatch();

		 	this.document = Dispatch.call(this.documents, "Open", textPath)
		 			.toDispatch();
			this.selection = this.word.getProperty("Selection").toDispatch();
			this.find = Dispatch.call(this.selection, "Find").toDispatch();
			this.paragraphs = Dispatch.get(document, "Paragraphs").toDispatch();
			this.tables = Dispatch.get(document, "Tables").toDispatch();
			this.range = Dispatch.get(selection, "Range").toDispatch();
		} catch (Exception ex) {
			ex.printStackTrace();
			System.out.println(ex.getCause().toString());
			ex.printStackTrace();
		}
		saveAsOutputFile();
		closeTemplate();
		insertWord();
		closeOutWord();
		quit();
		ComThread.Release();
	}

	/**
	 *          
	 * 
	 * @return      doc      
	 * 
	 */

	protected void quit() {
		if (this.word != null) {
			this.word.invoke("Quit", new Variant[] {});
			this.word = null;
		}
	}

	protected void saveAsOutputFile() {
		if (this.document != null) {
			Dispatch.invoke(this.document, "SaveAs", Dispatch.Method,
					new Object[] { this.outWord, new Variant(0) }, new int[1]);
		}
	}

	protected void closeTemplate() {
		if (this.textPath != null && this.document != null) {
			Dispatch.call(this.document, "Close", new Variant(false));
			this.document = null;
		}
	}
	
	protected void closeOutWord() {
		if (this.outWord != null && this.document != null) {
			Dispatch.call(this.document, "Close", new Variant(false));
			this.document = null;
		}
	}

	public boolean insertWord() {
		if (info != null && info.size() > 0) {
			for (Iterator it = info.keySet().iterator(); it.hasNext();) {
				String lkey = it.next().toString(); //  
				String lvalue = (String) info.get(lkey);//  
				replaceWord(lkey, lvalue);
			}
		}
		return false;

	}

	/**
	 *       word           
	 * 
	 * @param textPath
	 *                word  
	 * @param targetWord
	 *                   
	 * @param replaceWord
	 *                    
	 */
	public static void replaceWord(String targetWord, String replaceWord) {
		ActiveXComponent app = new ActiveXComponent("Word.Application");//   word
		try {
			app.setProperty("Visible", new Variant(false));//   word   
			Dispatch docs = app.getProperty("Documents").toDispatch();
			Dispatch doc = Dispatch.invoke(
					docs,
					"Open",
					Dispatch.Method,
					new Object[] { outWord, new Variant(false),
							new Variant(false) }, new int[1]).toDispatch();
			//   word  ,            false,               ,
			//           ,         。

			Dispatch selection = app.getProperty("Selection").toDispatch();//    Selection  
			Dispatch.call(selection, "HomeKey", new Variant(6));//     
		 	Dispatch find = Dispatch.call(selection, "Find").toDispatch();//   Find  

			Dispatch.put(find, "Text", targetWord);//      targetWord

			Dispatch.call(find, "Execute");//     

			Dispatch.put(selection, "Text", replaceWord);//    replaceWord

			Dispatch.call(doc, "Save");//   

			Dispatch.call(doc, "Close", new Variant(false));
		
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			
		}
	}
 
	/**
	 *     word  
	 * 
	 * @param txtContent
	 *               word     
	 * @param fileName
	 *                word    
	 */
	public static void createWordFile(String txtContent, String fileName) {
		ActiveXComponent app = new ActiveXComponent("Word.Application");//   word
		try {
			app.setProperty("Visible", new Variant(false));//   word   
			Dispatch docs = app.getProperty("Documents").toDispatch();
			Dispatch doc = Dispatch.call(docs, "Add").toDispatch();
			Dispatch selection = Dispatch.get(app, "Selection").toDispatch();
			Dispatch.put(selection, "Text", txtContent);
			Dispatch.call((Dispatch) Dispatch.call(app, "WordBasic")
					.getDispatch(), "FileSaveAs", fileName);
			Variant f = new Variant(false);
			Dispatch.call(doc, "Close", f);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			app.invoke("Quit", new Variant[] {});
			app.safeRelease();
		}
	}

	/**
	 *      txt     word
	 * 
	 * @param txt
	 *            txt    
	 * @param wordFile
	 *            word  
	 */
	public static void createWordWithTxt(String txt, String wordFile) {
		String txtContent = null;
		try {
			txtContent = bufferedReader(txt);
		} catch (IOException e) {
			e.printStackTrace();
		}
		createWordFile(txtContent, wordFile);
	}

	/**
	 *    
	 * 
	 * @param path
	 * @return
	 * @throws IOException
	 */
	public static String bufferedReader(String path) throws IOException {
		File file = new File(path);
		if (!file.exists() || file.isDirectory())
			throw new FileNotFoundException();
		BufferedReader br = new BufferedReader(new FileReader(file));
		String temp = null;
		StringBuffer sb = new StringBuffer();
		temp = br.readLine();
		while (temp != null) {
			sb.append(temp + " ");
			temp = br.readLine();
		}
		return sb.toString();
	}

	/**
	 *     word              
	 * 
	 * @param wordFile
	 *            word  
	 * @param imagePath
	 *                    
	 * @param str
	 *                    
	 */
	public static void insertImage(String wordFile, String imagePath,
			String tarStr) {
		ActiveXComponent app = new ActiveXComponent("Word.Application");//   word
		try {
			app.setProperty("Visible", new Variant(false));//   word   

			Dispatch docs = app.getProperty("Documents").toDispatch();

			Dispatch doc = Dispatch.invoke(
					docs,
					"Open",
					Dispatch.Method,
					new Object[] { wordFile, new Variant(false),
							new Variant(false) }, new int[1]).toDispatch();
			//   word  ,            false,               ,
			//           ,         。

			Dispatch selection = app.getProperty("Selection").toDispatch();
			Dispatch.call(selection, "HomeKey", new Variant(6));//     
			Dispatch find = Dispatch.call(selection, "Find").toDispatch();//   Find  
			Dispatch.put(find, "Text", tarStr);//      tarStr
			Dispatch.call(find, "Execute");//     
			Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
					"AddPicture", imagePath);//          
			Dispatch.call(doc, "Save");//   
			Dispatch.call(doc, "Close", new Variant(false));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			app.invoke("Quit", new Variant[] {});
			app.safeRelease();
		}
	}

	/**
	 *    word             
	 * 
	 * @param wordFile  word  
	 * @param pos
	 *                
	 * 
	 * @param numCols
	 *              
	 * @param numRows
	 *              
	 */
	public static void createTable(String wordFile, String pos, int numCols,
			int numRows) {
		ActiveXComponent app = new ActiveXComponent("Word.Application");//   word
		Dispatch selection = null;
		Dispatch doc = null;
		Dispatch docs = null;
		boolean b = false;
		try {
			app.setProperty("Visible", new Variant(false));//   word   

			docs = app.getProperty("Documents").toDispatch();

			doc = Dispatch.invoke(
					docs,
					"Open",
					Dispatch.Method,
					new Object[] { wordFile, new Variant(false),
							new Variant(false) }, new int[1]).toDispatch();
			//   word  ,            false,               ,
			//           ,         。

			selection = app.getProperty("Selection").toDispatch();
		} catch (Exception e) {
			e.printStackTrace();
		}
		if (pos == null || pos.equals(""))
			b = false;
		//  selection        
		Dispatch find = app.call(selection, "Find").toDispatch();
		//         
		Dispatch.put(find, "Text", pos);
		//     
		Dispatch.put(find, "Forward", "True");
		//     
		Dispatch.put(find, "Format", "True");
		//      
		Dispatch.put(find, "MatchCase", "True");
		//     
		Dispatch.put(find, "MatchWholeWord", "True");
		//      
		b = Dispatch.call(find, "Execute").getBoolean();
		//     
		if (b) {
			Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
			Dispatch range = Dispatch.get(selection, "Range").toDispatch();
			Dispatch newTable = Dispatch.call(tables, "Add", range,
					new Variant(numRows), new Variant(numCols)).toDispatch();
			Dispatch.call(selection, "MoveRight");
		} else
			System.out.println("         ,            。");
		try {
			Dispatch.call(doc, "Save");//   
			Dispatch.call(doc, "Close", new Variant(false));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			app.invoke("Quit", new Variant[] {});
			app.safeRelease();
		}

	} 
}

 3、テストTest.java
package com.cgrj.jacob;

import java.util.HashMap;
import java.util.Map;

import com.jacob.com.ComThread;

public class Text {
	public static void main(String[] args) {
		Map<String, String> info = new HashMap<String, String>();
		info.put("xwdd", "1234");
		info.put("xwr", "safdg");
	   
		WordMaker f = new WordMaker();   
        f.buildWord("f:\\d.doc", "f:\\aa.doc", info);
 
	}
}

 
Mapで置換する文字を保存
例えばwordテンプレートにxwddがあると「私」に置き換えられます 
しかし、現在2つの小さな問題が解決されなければならない.
1操作時にドキュメントを閉じなければなりません.そうしないと、エラーが発生します.
2,Webプロジェクトであれば,クライアント操作は実際にサーバ上で生成され操作されるが,これは我々が望む効果ではない.
    その後jsもwordを操作できることに気づいた彼はクライアントで操作していた.
 var word; 

word = new ActiveXObject("Word.Application");

var range = word.Range;

word.Visible = true;

var path = "filepath";

word.Documents.Open(path);

range = word.ActiveDocument.Bookmarks("bookmark").Range;

range.InsertBefore("      "); //       



//-----                  ----



//    ,      

range.select();//      

var psw='123'

word.ActiveDocument.BookMarks("bookmark").Range.Editors.Add(-1); //  :wdEditorEveryone=-1

word.ActiveDocument.Protect(3,false,psw,false,false);//  :wdAllowOnlyReading=3

//      

word.ActiveDocument.Unprotect(psw);



//-----------------------end--------------

 
http://516263736.blog.163.com/blog/static/7141143520107111425939/
 詳しい操作方法を書きました.
個人的にはwebプロジェクトをするとjavaで操作したほうがいいと思います.アップロードとダウンロードによりクライアントの操作を実現できます.結局クライアントがwordをインストールしたとは限らない
 
私が残した質問は達人が見ても手伝ってほしいです.