提取Word中指定内容

/**
 * 借助word书签及限制编辑功能提取word中指定内容
 * @author David
 *
 */
public class BookmarkReader {
	/**
	 * 基于Jacob,服务器端必需安装office
	 * 请将jacob-1.18-M2-x64.dll,jacob-1.18-M2-x86.dll放至%JAVA_HOME%/jre/bin下
	 */
	public static void main(String[] args) {
		File file = new File("D:/业务文档/测试.doc");
		BookmarkReader reader = new BookmarkReader(file);
		System.out.println(reader.getValue("jffddz"));
		reader.close();
	}

	private ActiveXComponent word;
	private Dispatch doc;
	private Dispatch bookMarks;

	public BookmarkReader(File file) {
		word = new ActiveXComponent("Word.Application");
		word.setProperty("Visible", new Variant(false));
		Dispatch documents = word.getProperty("Documents").toDispatch();
		doc = Dispatch.call(documents, "Open", file.getAbsolutePath())
				.toDispatch();
		bookMarks = ActiveXComponent.call(doc, "Bookmarks").toDispatch();
	}

	public String getValue(String key) {
		Dispatch rangeItem = Dispatch.call(bookMarks, "Item", key).toDispatch();
		if (rangeItem != null) {
			Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
			String value = Dispatch.get(range, "Text").getString();
			return value.substring(1, value.length() - 1).trim();
		}
		return null;
	}

	public void close() {
		Dispatch.call(doc, "Close", new Variant(false));
		word.invoke("Quit", new Variant[0]);
	}
}


你可能感兴趣的:(word,字段)