jacob操作word

 

/**
 * 
 */
package com.xaeds.taecs.common.util;

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

/**
 * @author Administrator
 * 
 */
public class WordBean {

	// word文档
	private Dispatch doc;

	// word运行程序对象
	private ActiveXComponent word;

	// 所有word文档集合
	private Dispatch documents;

	// 选定的范围或插入点
	private Dispatch selection;

	private boolean saveOnExit = true;

	public WordBean(boolean visible) throws Exception {
		if (word == null) {
			word = new ActiveXComponent("Word.Application");
			word.setProperty("Visible", new Variant(visible)); // 不可见打开word
			word.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
		}
		if (documents == null)
			documents = word.getProperty("Documents").toDispatch();
	}

	/**
	 * 设置退出时参数
	 * 
	 * @param saveOnExit
	 *            boolean true-退出时保存文件,false-退出时不保存文件
	 */
	public void setSaveOnExit(boolean saveOnExit) {
		this.saveOnExit = saveOnExit;
	}

	/**
	 * 创建一个新的word文档
	 * 
	 */
	public void createNewDocument() {
		doc = Dispatch.call(documents, "Add").toDispatch();
		selection = Dispatch.get(word, "Selection").toDispatch();
	}

	/**
	 * 打开一个已存在的文档
	 * 
	 * @param docPath
	 */
	public void openDocument(String docPath) {
		closeDocument();
		doc = Dispatch.call(documents, "Open", docPath).toDispatch();
		selection = Dispatch.get(word, "Selection").toDispatch();
	}

	/**
	 * 打开一个保护文档,
	 * 
	 * @param docPath
	 *            -文件全名
	 * @param pwd
	 *            -密码
	 */
	public void openDocumentOnlyRead(String docPath, String pwd)
			throws Exception {
		closeDocument();
		doc = Dispatch.callN(
				documents,
				"Open",
				new Object[] { docPath, new Variant(false), new Variant(true),
						new Variant(true), pwd, "", new Variant(false) })
				.toDispatch();
		selection = Dispatch.get(word, "Selection").toDispatch();
	}

	public void openDocument(String docPath, String pwd) throws Exception {
		closeDocument();
		doc = Dispatch.callN(
				documents,
				"Open",
				new Object[] { docPath, new Variant(false), new Variant(false),
						new Variant(true), pwd }).toDispatch();
		selection = Dispatch.get(word, "Selection").toDispatch();
	}

	/**
	 * 把选定的内容或插入点向上移动
	 * 
	 * @param pos
	 *            移动的距离
	 */
	public void moveUp(int pos) {
		if (selection == null)
			selection = Dispatch.get(word, "Selection").toDispatch();
		for (int i = 0; i < pos; i++)
			Dispatch.call(selection, "MoveUp");

	}

	/**
	 * 把选定的内容或者插入点向下移动
	 * 
	 * @param pos
	 *            移动的距离
	 */
	public void moveDown(int pos) {
		if (selection == null)
			selection = Dispatch.get(word, "Selection").toDispatch();
		for (int i = 0; i < pos; i++)
			Dispatch.call(selection, "MoveDown");
	}

	/**
	 * 把选定的内容或者插入点向左移动
	 * 
	 * @param pos
	 *            移动的距离
	 */
	public void moveLeft(int pos) {
		if (selection == null)
			selection = Dispatch.get(word, "Selection").toDispatch();
		for (int i = 0; i < pos; i++) {
			Dispatch.call(selection, "MoveLeft");
		}
	}

	/**
	 * 把选定的内容或者插入点向右移动
	 * 
	 * @param pos
	 *            移动的距离
	 */
	public void moveRight(int pos) {
		if (selection == null)
			selection = Dispatch.get(word, "Selection").toDispatch();
		for (int i = 0; i < pos; i++)
			Dispatch.call(selection, "MoveRight");
	}

	/**
	 * 把插入点移动到文件首位置
	 * 
	 */
	public void moveStart() {
		if (selection == null)
			selection = Dispatch.get(word, "Selection").toDispatch();
		Dispatch.call(selection, "HomeKey", new Variant(6));
	}
    public void enterStart(){
    	if (selection == null)
			selection = Dispatch.get(word, "Selection").toDispatch();
    	Dispatch.call(selection, "TypeParagraph");
    }
	/**
	 * 从选定内容或插入点开始查找文本
	 * 
	 * @param toFindText
	 *            要查找的文本
	 * @return boolean true-查找到并选中该文本,false-未查找到文本
	 */
	@SuppressWarnings("static-access")
	public boolean find(String toFindText) {
		if (toFindText == null || toFindText.equals(""))
			return false;
		// 从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 toFindText
	 *            查找字符串
	 * @param newText
	 *            要替换的内容
	 * @return
	 */
	public boolean replaceText(String toFindText, String newText) {
		if (!find(toFindText))
			return false;
		Dispatch.put(selection, "Text", newText);
		return true;
	}

	/**
	 * 全局替换文本
	 * 
	 * @param toFindText
	 *            查找字符串
	 * @param newText
	 *            要替换的内容
	 */
	public void replaceAllText(String toFindText, String newText) {
		while (find(toFindText)) {
			Dispatch.put(selection, "Text", newText);
			Dispatch.call(selection, "MoveRight");
		}
	}

	/**
	 * 在当前插入点插入字符串
	 * 
	 * @param newText
	 *            要插入的新字符串
	 */
	public void insertText(String newText) {
		Dispatch.put(selection, "Text", newText);
	}

	/**
	 * 
	 * @param toFindText
	 *            要查找的字符串
	 * @param imagePath
	 *            图片路径
	 * @return
	 */
	public boolean replaceImage(String toFindText, String imagePath) {
		if (!find(toFindText))
			return false;
		Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
				"AddPicture", imagePath);
		return true;
	}

	/**
	 * 全局替换图片
	 * 
	 * @param toFindText
	 *            查找字符串
	 * @param imagePath
	 *            图片路径
	 */
	public void replaceAllImage(String toFindText, String imagePath) {
		while (find(toFindText)) {
			Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
					"AddPicture", imagePath);
			Dispatch.call(selection, "MoveRight");
		}
	}

	/**
	 * 在当前插入点插入图片
	 * 
	 * @param imagePath
	 *            图片路径
	 */
	public void insertImage(String imagePath) {
		Dispatch.call(Dispatch.get(selection, "InLineShapes").toDispatch(),
				"AddPicture", imagePath);
	}

	  /** 
     * 合并当前表格指定的单元格 如果需要一次合并几个单元格只需要指出第一个单元格和最后一个单元格 
     *  
     * @param fstCellRowIndex 
     *            第一个单元格的行索引 
     * @param fstCellColIndex 
     *            第一个单元格的列索引 
     * @param secCellRowIndex 
     *            第二个单元格的行索引 
     * @param secCellColIndex 
     *            第二个单元格的列索引 
     */ 
	public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
			int secCellRowIdx, int secCellColIdx) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		Dispatch fstCell = Dispatch.call(table, "Cell",
				new Variant(fstCellRowIdx), new Variant(fstCellColIdx))
				.toDispatch();
		Dispatch secCell = Dispatch.call(table, "Cell",
				new Variant(secCellRowIdx), new Variant(secCellColIdx))
				.toDispatch();
		Dispatch.call(fstCell, "Merge", secCell);
	}

	/**
	 * 在指定的单元格里填写数据
	 * 
	 * @param tableIndex
	 * @param cellRowIdx
	 * @param cellColIdx
	 * @param txt
	 */
	public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
			String txt) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
				new Variant(cellColIdx)).toDispatch();
		Dispatch.call(cell, "Select");
		Dispatch.put(selection, "Text", txt);
	}

	/**
	 * 获得指定的单元格里数据
	 * 
	 * @param tableIndex
	 * @param cellRowIdx
	 * @param cellColIdx
	 * @return
	 */
	public String getTxtFromCell(int tableIndex, int cellRowIdx, int cellColIdx) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
				new Variant(cellColIdx)).toDispatch();
		Dispatch.call(cell, "Select");
		String ret = "";
		ret = Dispatch.get(selection, "Text").toString();
		ret = ret.substring(0, ret.length() - 1); // 去掉最后的回车符;
		return ret;
	}

	/**
	 * 在当前文档拷贝剪贴板数据
	 * 
	 * @param pos
	 */
	public void pasteExcelSheet(String pos) {
		moveStart();
		if (this.find(pos)) {
			Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
			Dispatch.call(textRange, "Paste");
		}
	}

	/**
	 * 在当前文档指定的位置拷贝表格
	 * 
	 * @param pos
	 *            当前文档指定的位置
	 * @param tableIndex
	 *            被拷贝的表格在word文档中所处的位置
	 */
	public void copyTable(String pos, int tableIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		Dispatch range = Dispatch.get(table, "Range").toDispatch();
		Dispatch.call(range, "Copy");
		if (this.find(pos)) {
			Dispatch textRange = Dispatch.get(selection, "Range").toDispatch();
			Dispatch.call(textRange, "Paste");
		}
	}

	/**
	 * 在当前文档指定的位置拷贝来自另一个文档中的表格
	 * 
	 * @param anotherDocPath
	 *            另一个文档的磁盘路径
	 * @param tableIndex
	 *            被拷贝的表格在另一格文档中的位置
	 * @param pos
	 *            当前文档指定的位置
	 */
	public void copyTableFromAnotherDoc(String anotherDocPath, int tableIndex,
			String pos) {
		Dispatch doc2 = null;
		try {
			doc2 = Dispatch.call(documents, "Open", anotherDocPath)
					.toDispatch();
			// 所有表格
			Dispatch tables = Dispatch.get(doc2, "Tables").toDispatch();
			// 要填充的表格
			Dispatch table = Dispatch.call(tables, "Item",
					new Variant(tableIndex)).toDispatch();
			Dispatch range = Dispatch.get(table, "Range").toDispatch();
			Dispatch.call(range, "Copy");
			if (this.find(pos)) {
				Dispatch textRange = Dispatch.get(selection, "Range")
						.toDispatch();
				Dispatch.call(textRange, "Paste");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc2 != null) {
				Dispatch.call(doc2, "Close", new Variant(saveOnExit));
				doc2 = null;
			}
		}
	}

	/**
	 * 在当前文档指定的位置拷贝来自另一个文档中的图片
	 * 
	 * @param anotherDocPath
	 *            另一个文档的磁盘路径
	 * @param shapeIndex
	 *            被拷贝的图片在另一格文档中的位置
	 * @param pos
	 *            当前文档指定的位置
	 */
	public void copyImageFromAnotherDoc(String anotherDocPath, int shapeIndex,
			String pos) {
		Dispatch doc2 = null;
		try {
			doc2 = Dispatch.call(documents, "Open", anotherDocPath)
					.toDispatch();
			Dispatch shapes = Dispatch.get(doc2, "InLineShapes").toDispatch();
			Dispatch shape = Dispatch.call(shapes, "Item",
					new Variant(shapeIndex)).toDispatch();
			Dispatch imageRange = Dispatch.get(shape, "Range").toDispatch();
			Dispatch.call(imageRange, "Copy");
			if (this.find(pos)) {
				Dispatch textRange = Dispatch.get(selection, "Range")
						.toDispatch();
				Dispatch.call(textRange, "Paste");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (doc2 != null) {
				Dispatch.call(doc2, "Close", new Variant(saveOnExit));
				doc2 = null;
			}
		}
	}

	/**
	 * 创建表格
	 * 
	 * @param pos
	 *            位置
	 * @param cols
	 *            列数
	 * @param rows
	 *            行数
	 */
	public void createTable(String pos, int numCols, int numRows) {
		if (find(pos)) {
			Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
			Dispatch range = Dispatch.get(selection, "Range").toDispatch();
			@SuppressWarnings("unused")
			Dispatch newTable = Dispatch.call(tables, "Add", range,
					new Variant(numRows), new Variant(numCols),new Variant(1)).toDispatch();
			Dispatch.call(selection, "MoveRight");
		} else {
			Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
			Dispatch range = Dispatch.get(selection, "Range").toDispatch();
			@SuppressWarnings("unused")
			Dispatch newTable = Dispatch.call(tables, "Add", range,
					new Variant(numRows), new Variant(numCols),new Variant(1)).toDispatch();
			Dispatch.call(selection, "MoveRight");
		}
	}

	/**
	 * 在指定行前面增加行
	 * 
	 * @param tableIndex
	 *            word文件中的第N张表(从1开始)
	 * @param rowIndex
	 *            指定行的序号(从1开始)
	 */
	public void addTableRow(int tableIndex, int rowIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
		Dispatch row = Dispatch.call(rows, "Item", new Variant(rowIndex))
				.toDispatch();
		Dispatch.call(rows, "Add", new Variant(row));
	}

	/**
	 * 在第1行前增加一行
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 */
	public void addFirstTableRow(int tableIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
		Dispatch row = Dispatch.get(rows, "First").toDispatch();
		Dispatch.call(rows, "Add", new Variant(row));
	}

	/**
	 * 在最后1行前增加一行
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 */
	public void addLastTableRow(int tableIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
		Dispatch row = Dispatch.get(rows, "Last").toDispatch();
		Dispatch.call(rows, "Add", new Variant(row));
	}

	/**
	 * 增加一行
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 */
	public void addRow(int tableIndex) {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch rows = Dispatch.get(table, "Rows").toDispatch();
		Dispatch.call(rows, "Add");
	}

	/**
	 * 增加一列
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 */
	public void addCol(int tableIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
		Dispatch.call(cols, "Add").toDispatch();
		Dispatch.call(cols, "AutoFit");
	}

	/**
	 * 在指定列前面增加表格的列
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 * @param colIndex
	 *            制定列的序号 (从1开始)
	 */
	public void addTableCol(int tableIndex, int colIndex) {
		// 所有表格
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
		System.out.println(Dispatch.get(cols, "Count"));
		Dispatch col = Dispatch.call(cols, "Item", new Variant(colIndex))
				.toDispatch();
		// Dispatch col = Dispatch.get(cols, "First").toDispatch();
		Dispatch.call(cols, "Add", col).toDispatch();
		Dispatch.call(cols, "AutoFit");
	}

	/**
	 * 在第1列前增加一列
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 */
	public void addFirstTableCol(int tableIndex) {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
		Dispatch col = Dispatch.get(cols, "First").toDispatch();
		Dispatch.call(cols, "Add", col).toDispatch();
		Dispatch.call(cols, "AutoFit");
	}

	/**
	 * 在最后一列前增加一列
	 * 
	 * @param tableIndex
	 *            word文档中的第N张表(从1开始)
	 */
	public void addLastTableCol(int tableIndex) {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		// 要填充的表格
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		// 表格的所有行
		Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
		Dispatch col = Dispatch.get(cols, "Last").toDispatch();
		Dispatch.call(cols, "Add", col).toDispatch();
		Dispatch.call(cols, "AutoFit");
	}

	/**
	 * 自动调整表格
	 * 
	 */
	public void autoFitTable() {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		int count = Dispatch.get(tables, "Count").toInt();
		for (int i = 0; i < count; i++) {
			Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
					.toDispatch();
			Dispatch cols = Dispatch.get(table, "Columns").toDispatch();
			Dispatch.call(cols, "AutoFit");
		}
	}

	/**
	 * 调用word里的宏以调整表格的宽度,其中宏保存在document下
	 * 
	 */
	public void callWordMacro() {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		int count = Dispatch.get(tables, "Count").toInt();
		Variant vMacroName = new Variant("Normal.NewMacros.tableFit");
		@SuppressWarnings("unused")
		Variant vParam = new Variant("param1");
		@SuppressWarnings("unused")
		Variant para[] = new Variant[] { vMacroName };
		for (int i = 0; i < count; i++) {
			Dispatch table = Dispatch.call(tables, "Item", new Variant(i + 1))
					.toDispatch();
			Dispatch.call(table, "Select");
			Dispatch.call(word, "Run", "tableFitContent");
		}
	}

	/**
	 * 设置当前选定内容的字体
	 * 
	 * @param boldSize
	 * @param italicSize
	 * @param underLineSize
	 *            下划线
	 * @param colorSize
	 *            字体颜色
	 * @param size
	 *            字体大小
	 * @param name
	 *            字体名称
	 */
	public void setFont(boolean bold, boolean italic, boolean underLine,
			 String size, String name) {
		Dispatch font = Dispatch.get(selection, "Font").toDispatch();
		Dispatch.put(font, "Name", new Variant(name));
		Dispatch.put(font, "Bold", new Variant(bold));
		Dispatch.put(font, "Italic", new Variant(italic));
		Dispatch.put(font, "Underline", new Variant(underLine));
		Dispatch.put(font, "Size", size);
	}

	/**
	 * 设置单元格被选中
	 * 
	 * @param tableIndex
	 * @param cellRowIdx
	 * @param cellColIdx
	 */
	public void setTableCellSelected(int tableIndex, int cellRowIdx,
			int cellColIdx) {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		Dispatch table = Dispatch.call(tables, "Item", new Variant(tableIndex))
				.toDispatch();
		Dispatch cell = Dispatch.call(table, "Cell", new Variant(cellRowIdx),
				new Variant(cellColIdx)).toDispatch();
		Dispatch.call(cell, "Select");
	}

	/**
	 * 设置选定单元格的垂直对起方式, 请使用setTableCellSelected选中一个单元格
	 * 
	 * @param align
	 *            0-顶端, 1-居中, 3-底端
	 */
	public void setCellVerticalAlign(int verticalAlign) {
		Dispatch cells = Dispatch.get(selection, "Cells").toDispatch();
		Dispatch.put(cells, "VerticalAlignment", new Variant(verticalAlign));
	}

	/**
	 * 设置当前文档中所有表格水平居中方式及其它一些格式,用在将word文件转化为html中,针对申报表
	 */
	public void setApplyTableFormat() {
		Dispatch tables = Dispatch.get(doc, "Tables").toDispatch();
		int tabCount = Integer
				.valueOf(Dispatch.get(tables, "Count").toString()); // System.out.println(tabCount);
		System.out
				.println("*******************************************************");
		for (int i = 1; i <= tabCount; i++) {
			Dispatch table = Dispatch.call(tables, "Item", new Variant(i))
					.toDispatch();
			Dispatch rows = Dispatch.get(table, "Rows").toDispatch();

			if (i == 1) {
				Dispatch.put(rows, "Alignment", new Variant(2)); // 1-居中,2-Right
				continue;
			}
			Dispatch.put(rows, "Alignment", new Variant(1)); // 1-居中
			Dispatch.call(table, "AutoFitBehavior", new Variant(1));// 设置自动调整表格方式,1-根据窗口自动调整
			Dispatch.put(table, "PreferredWidthType", new Variant(1));
			Dispatch.put(table, "PreferredWidth", new Variant(700));
			System.out.println(Dispatch.get(rows, "HeightRule").toString());
			Dispatch.put(rows, "HeightRule", new Variant(1)); // 0-自动wdRowHeightAuto,1-最小值wdRowHeightAtLeast,
																// 2-固定wdRowHeightExactly
			Dispatch.put(rows, "Height", new Variant(0.04 * 28.35));
			// int oldAlign = Integer.valueOf(Dispatch.get(rows,
			// "Alignment").toString());
			// System.out.println("Algin:" + oldAlign);
		}
	}

	/**
	 * 设置段落格式
	 * 
	 * @param alignment
	 *            0-左对齐, 1-右对齐, 2-右对齐, 3-两端对齐, 4-分散对齐
	 * @param lineSpaceingRule
	 * @param lineUnitBefore
	 * @param lineUnitAfter
	 * @param characterUnitFirstLineIndent
	 */
	public void setParagraphsProperties(int alignment, int lineSpaceingRule,
			int lineUnitBefore, int lineUnitAfter,
			int characterUnitFirstLineIndent) {
		Dispatch paragraphs = Dispatch.get(selection, "Paragraphs")
				.toDispatch();
		Dispatch.put(paragraphs, "Alignment", new Variant(alignment)); // 对齐方式
		Dispatch.put(paragraphs, "LineSpacingRule", new Variant(
				lineSpaceingRule)); // 行距
		Dispatch.put(paragraphs, "LineUnitBefore", new Variant(lineUnitBefore)); // 段前
		Dispatch.put(paragraphs, "LineUnitAfter", new Variant(lineUnitAfter)); // 段后
		Dispatch.put(paragraphs, "CharacterUnitFirstLineIndent", new Variant(
				characterUnitFirstLineIndent)); // 首行缩进字符数
	}

	/**
	 * 设置当前段落格式, 使用前,请先选中段落
	 */
	public void getParagraphsProperties() {
		Dispatch paragraphs = Dispatch.get(selection, "Paragraphs")
				.toDispatch();
		String val = Dispatch.get(paragraphs, "LineSpacingRule").toString(); // 行距
		val = Dispatch.get(paragraphs, "Alignment").toString(); // 对齐方式
		val = Dispatch.get(paragraphs, "LineUnitBefore").toString(); // 段前行数
		val = Dispatch.get(paragraphs, "LineUnitAfter").toString(); // 段后行数
		val = Dispatch.get(paragraphs, "FirstLineIndent").toString(); // 首行缩进
		val = Dispatch.get(paragraphs, "CharacterUnitFirstLineIndent")
				.toString(); // 首行缩进字符数
	}

	/**
	 * 文件保存或另存为
	 * 
	 * @param savePath
	 *            保存或另存为路径
	 */
	public void save(String savePath) {
		Dispatch.call(Dispatch.call(word, "WordBasic").getDispatch(),
				"FileSaveAs", savePath);
	}

	/**
	 * 文件保存为html格式
	 * 
	 * @param savePath
	 * @param htmlPath
	 */
	public void saveAsHtml(String htmlPath) {
		Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
				htmlPath, new Variant(8) }, new int[1]);
	}

	/**
	 * 关闭文档
	 * 
	 * @param val
	 *            0不保存修改 -1 保存修改 -2 提示是否保存修改
	 */
	public void closeDocument(int val) {
		Dispatch.call(doc, "Close", new Variant(val));
		doc = null;
	}

	/**
	 * 关闭当前word文档
	 * 
	 */
	public void closeDocument() {
		if (doc != null) {
			Dispatch.call(doc, "Save");
			Dispatch.call(doc, "Close", new Variant(saveOnExit));
			doc = null;
		}
	}

	public void closeDocumentWithoutSave() {
		if (doc != null) {
			Dispatch.call(doc, "Close", new Variant(false));
			doc = null;
		}
	}

	/**
	 * 关闭全部应用
	 * 
	 */
	public void close() {
		// closeDocument();
		if (word != null) {
			Dispatch.call(word, "Quit");
			word = null;
		}
		selection = null;
		documents = null;
	}

	/**
	 * 打印当前word文档
	 * 
	 */
	public void printFile() {
		if (doc != null) {
			Dispatch.call(doc, "PrintOut");
		}
	}

	/**
	 * 保护当前档,如果不存在, 使用expression.Protect(Type, NoReset, Password)
	 * 
	 * @param pwd
	 *            WdProtectionType 可以是下列 WdProtectionType 常量之一:
	 *            1-wdAllowOnlyComments, 2-wdAllowOnlyFormFields,
	 *            0-wdAllowOnlyRevisions, -1-wdNoProtection,
	 *            3-wdAllowOnlyReading
	 * 
	 *            使用参照 main1()
	 */
	public void protectedWord(String pwd) {
		String protectionType = Dispatch.get(doc, "ProtectionType").toString();
		if (protectionType.equals("-1")) {
			Dispatch.call(doc, "Protect", new Variant(3), new Variant(true),
					pwd);
		}
	}

	/**
	 * 解除文档保护,如果存在
	 * 
	 * @param pwd
	 *            WdProtectionType 常量之一(Long 类型,只读):
	 *            1-wdAllowOnlyComments,2-wdAllowOnlyFormFields、
	 *            0-wdAllowOnlyRevisions,-1-wdNoProtection, 3-wdAllowOnlyReading
	 * 
	 *            使用参照 main1()
	 */
	public void unProtectedWord(String pwd) {
		String protectionType = Dispatch.get(doc, "ProtectionType").toString();
		if (protectionType.equals("3")) {
			Dispatch.call(doc, "Unprotect", pwd);
		}
	}

	/**
	 * 设置word文档安全级别
	 * 
	 * @param value
	 *            1-msoAutomationSecurityByUI 使用“安全”对话框指定的安全设置。
	 *            2-msoAutomationSecurityForceDisable
	 *            在程序打开的所有文件中禁用所有宏,而不显示任何安全提醒。 3-msoAutomationSecurityLow
	 *            启用所有宏,这是启动应用程序时的默认值。
	 */
	public void setAutomationSecurity(int value) {
		word.setProperty("AutomationSecurity", new Variant(value));
	}

	/**
	 * 读取文档中第paragraphsIndex段文字的内容;
	 * 
	 * @param paragraphsIndex
	 * @return
	 */
	public String getParagraphs(int paragraphsIndex) {
		String ret = "";
		Dispatch paragraphs = Dispatch.get(doc, "Paragraphs").toDispatch(); // 所有段落
		int paragraphCount = Dispatch.get(paragraphs, "Count").getInt(); // 一共的段落数
		Dispatch paragraph = null;
		Dispatch range = null;
		if (paragraphCount > paragraphsIndex && 0 < paragraphsIndex) {
			paragraph = Dispatch.call(paragraphs, "Item",
					new Variant(paragraphsIndex)).toDispatch();
			range = Dispatch.get(paragraph, "Range").toDispatch();
			ret = Dispatch.get(range, "Text").toString();
		}
		return ret;
	}

	/**
	 * 设置页眉文字
	 * 
	 * @param cont
	 * @return
	 * 
	 *         Sub AddHeaderText() '设置页眉或页脚中的文字 '由 Headers、Footers 和
	 *         HeaderFooter 属性返回 HeaderFooter 对象。下列示例更改当前页眉中的文字。 With
	 *         ActiveDocument.ActiveWindow.View .SeekView =
	 *         wdSeekCurrentPageHeader Selection.HeaderFooter.Range.Text =
	 *         "Header text" .SeekView = wdSeekMainDocument End With End Sub
	 */
	public void setHeaderContent(String cont) {
		Dispatch activeWindow = Dispatch.get(doc, "ActiveWindow").toDispatch();
		Dispatch view = Dispatch.get(activeWindow, "View").toDispatch();
		// Dispatch seekView = Dispatch.get(view, "SeekView").toDispatch();
		Dispatch.put(view, "SeekView", new Variant(9)); // wdSeekCurrentPageHeader-9

		Dispatch headerFooter = Dispatch.get(selection, "HeaderFooter")
				.toDispatch();
		Dispatch range = Dispatch.get(headerFooter, "Range").toDispatch();
		Dispatch.put(range, "Text", new Variant(cont));
		// String content = Dispatch.get(range, "Text").toString();
		Dispatch font = Dispatch.get(range, "Font").toDispatch();

		Dispatch.put(font, "Name", new Variant("宋体 (中文正文)"));
		Dispatch.put(font, "Bold", new Variant(false));
		// Dispatch.put(font, "Italic", new Variant(true));
		// Dispatch.put(font, "Underline", new Variant(true));
		Dispatch.put(font, "Size", 9);

		Dispatch.put(view, "SeekView", new Variant(0)); // wdSeekMainDocument-0恢复视图;
	}
}
Java使用Jacob操作word 近期项目需要根据word模板动态生成word文档,在网上看了些资料,在介绍的几种方法中选择了jacob方式,根据网上的资料,能解决大部分的问题,比如,生成表格,设置字体、段落格式,插入图片、设置图片格式。 可是项目中生成的word 文档还需要生成目录页,分割章节,网上找了很多资料,都没找到相关的方法,最后看到一篇博客,提供了一个思路,Java通过jacob操作office的宏,加上之前有过写宏的 阅读详情

相关推荐

Jacob库在Java中操作Word文档的实践指南

Jacob(Java COM Bridge)是一个开源库,它允许Java应用程序通过COM接口与Windows应用程序交互。使用Jacob,开发者可以在Java环境中操作如Microsoft Office等桌面软件,实现自动化办公的需求。COM(Component Object Model,组件对象模型)是由微软提出的一种软件组件架构,它定义了组件对象之间进行交互的标准。在Windows平台上,许多应用程序都支持通过COM接口与其他应用或服务进行通信。

weixin_42518874的博客 851

word文档直接嵌入到jsp页面

继上次的把附件内容显示在jsp页面,这次查资料发现可以把word文档直接嵌入到jsp页面。文档的内容格式不会 发生变化,很强大的一个功能     第一步 下载jacob                 下载地址:http://www.chinait8.net/download/ide/4107.html     第二步  解压下载的文件,将其中dll文件放入tomcat

qq_20507067的博客 2929

将word文档嵌入到jsp页面的详细步骤

近日在项目中需要将word文档嵌入到jsp页面中,遇到这个问题,首先想到的解决方法便是将word内容读取,然后放入jsp中,可是这样做有一个难点,就是读取word的格式,图片以及表格等内容,由于在前几日用过jacob将word转换为pdf文件,所以试想,能不能将word转换为htm文件,直接展示就容易很多,经过研究,果然可以做到,步骤如下:

jacob操作word文档

Jacob 是Java-COM Bridge的缩写,它在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。Jacob下载的地址为:http://sourceforge.net/project/showfiles.php?group_id=109543&amp;package_id=118368配置:(1)将...

gcguchao的博客 441

jacob + servlet + jsp demo

将常用文件转化为PDF文件,文件中有包哦,可以部署的,

使用jacob把word转化成html

使用jacob把word转化成html,详细步骤。

java通过jacob操作word的一些实践

前言 JACOB(java -com bridge)是一个 JAVA到微软的COM接口的桥梁。使用JACOB允许任何JVM访问COM对象,从而使JAVA应用程序能够调用COM对象。关于JACOB的很多基础知识网上也是很多文章介绍,我也是根据这些资料进行开发的。粘上两个我保存的文章 jacob的使用方法总结 java操作word文档(jacob) 本文主要是讲解当遇到网上查找不到的word方法时候,需要怎么处理,以及自己使用过程中的注意事项。 正文 1、网上关于JACOB的介绍很多,但是都是基础功能没有官方

l13020227067的博客 1197

卡尔曼滤波调参避坑指南:Q/R参数怎么设?实测5种传感器场景

本文针对卡尔曼滤波在工程实践中Q/R参数设置的难题,提供了一套实用的调参避坑指南。通过分析过程噪声方差Q与测量噪声方差R的物理意义与博弈关系,并结合温度传感器、陀螺仪、超声波测距等五种典型传感器场景的实测效果对比,总结出从噪声估算、离线仿真到收敛测试的系统性调参方法论,帮助工程师快速实现稳定有效的滤波效果。

weixin_29174141的博客 809

Java操作Microsoft Word之jacob

青春乐园   原文链接http://www.cnblogs.com/hzj-/articles/1732567.html Java操作Microsoft Word之jacob 现在我们一起来看看,用Java如何操作Microsoft Word。   jacob,官网是http://danadler.com/jacob 这是一个开源的工具。最新版本1.7

abs44544的专栏 753

从ADS到SystemVue:当简单链路预算不够用时,我的射频系统级仿真方案升级实录

本文详细介绍了从ADS到SystemVue的射频系统级仿真升级路径,重点分析了基础链路预算在多端口元件和复杂场景下的局限性,并提供了SystemVue在非线性系统验证和跨域协同分析中的优势。通过实际案例展示了如何平滑迁移工具链,提升仿真精度和效率,适用于5G、毫米波雷达等现代射频系统设计。

weixin_34233974的博客 345

【低空经济】森林火情高精度监测与早期预警无人机巡护方案

在全球范围内,森林火灾已成为一个严重的生态和社会问题。它不仅对自然生态系统造成了毁灭性的影响,还对人类的生命财产安全构成了极大的威胁。根据国际森林发展组织的统计,全球每年因森林火灾造成的经济损失高达数百亿美元,甚至在某些年份,火灾损失占到某些国家国民经济总量的相当一部分。因此,开展高效的森林火情监测与早期预警工作显得尤为重要。随着科技的发展,无人机作为新兴的监测工具,以其高效、灵活和经济的特点在森林火灾监测领域展现出了巨大的潜力。

2502_92579126的博客 1213

jacob操作excel、word、AutoCAD分享

零、导读 这是使用jacob操作Word和Excel的教程,因为看不懂官方文档(英语不好,翻译太菜)所以选择去找找教程。 jacob可以操作的 1、jacob 操作 cad相关资料 对象方法和操作,里面的例子都是 http://entercad.ru/acadauto.en/ 2、jacob操作word和Excel相关资料和文档(也有PPT access等资料) 这个微软官方有中文版翻译在左下角,...

qq_35799668的博客 4471

STM32F407 BootLoader实战:从零搭建到OTA升级(附完整源码)

本文详细介绍了为STM32F407微控制器从零搭建BootLoader并实现稳定OTA升级的完整实战指南。内容涵盖Flash分区规划、链接脚本配置、核心跳转逻辑、中断向量表重定向、可靠的升级流程设计,并深入探讨了双备份与回滚机制以提升工业级可靠性。文章提供了可直接使用的代码框架,并分享了关键调试技巧,帮助开发者快速掌握STM32远程固件更新技术。

weixin_29192211的博客 445

jacob 操作word

1. 首先下载jacob-1.18.zip,解压后有两个文件jacob.jar和jacob.dll。需要把jacob.jar放到你工程的classpath中并且把jacob.dll放到jdk的bin目录下(D:\Program Files\Java\jdk1.8.0_101\bin)目录下或者系统的system32其他相应的目录下。 放到jdk/bin目录下,时常会出现jacob....

dexifu0748的博客 300

Java + Selenium + TestNg + Allure Web UI 自动化

我们知道,在Python中针对Web UI自动化有Python + Selenium + Pytest/Unittest +Allure的技术栈。那么对于Java而言,也有其独特的Web UI 自动化技术栈。相同的,我们同样的运用Selenium框架,测试报告同样运用Allure。不同的是,我们运用的语言由Python转化为了Java,测试用例管理框架从Pytest转化为了TestNG。

qq_45594960的博客 1913

OpenCASCADE完整教程专栏完整目录

OpenCASCADE完整教程专栏完整目录

希望我的博客,能帮上你解决学习中工作中所遇到的问题 9705

Jacob操作Word文档转换-XXOO

前言 JACOB一个Java-COM中间件.通过这个组件你可以在Java应用程序中调用COM组件和Win32程序库。 一、准备 <!--添加本地的jacob.jar包--> <dependency> <groupId>com.jacob</groupId> <artifactId>jacob</artifactId> <version>1.19</version> <

JueDream的博客 641

主题035:计算流体力学(CFD)

计算流体力学(Computational Fluid Dynamics, CFD)是利用数值方法求解流体流动、传热传质等问题的学科。CFD已成为化学反应工程中反应器设计和优化的重要工具。∂ρ∂t+∇⋅(ρu)=0 \frac{\partial \rho}{\partial t} + \nabla \cdot (\rho \mathbf{u}) = 0 ∂t∂ρ​+∇⋅(ρu)=0对于不可压缩流动:∇⋅u=0 \nabla \cdot \mathbf{u} = 0 ∇⋅u=0动量方程:∂(ρu)∂t+∇⋅(ρ

kkchenjj的博客 269

利用Java-JACOB操作WORD文档2

利用Java-JACOB操作WORD文档2 JACOB是一个 JAVA到微软的COM接口的桥梁。使用JACOB允许任何JVM访问COM对象,从而使JAVA应用程序能够调用COM对象。如果你要对 MS Word、Excel 进行处理,JACOB 是一个好的选择。JACOB目前已经成为sourceforge(http://sourceforge.net/projects/jacob- project/)的一个开源项目,本文使用的版本是1.10.1。 生成WORD文档的简单讲解: 1. 初始

bb6893058的专栏 252

eNSP与我这24H2版本不兼容,路由器40错误。这该怎么处理(操作系统-windows)(相关搜索:虚拟机)

🏆本文收录于《全栈Bug调优(实战版)》专栏,主要记录项目实战过程中所遇到的Bug或因后果及提供真实有效的解决方案,希望能够助你一臂之力,帮你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!

**My Coding Family** 4112

Data-Structures-and-Algorithm-Analysis-in-Java.pdf

作者: Weiss, Mark A. 出版社: Addison Wesley Data Structures and Algorithm Analysis in Java is an “advanced algorithms” book that fits between traditional CS2 and Algorithms Analysis courses. In the old ACM Curriculum Guidelines, this course was known as CS7. This text is for readers who want to learn good programming and algorithm analysis skills simultaneously so that they can develop such programs with the maximum amo...

jacob如何操作word

首先,大家先要了解一下jacob ,官方的解释是Java COM Bridge,即java和 com组件间的桥梁,这里说说为什么我们用jacob操纵word。而不直接使用java去做? 这要原因:在Java开源世界没有很好工具来操作Word文档,POI对word操作还是很不完善,所以我们无法使用它很方便操作word文档来满足我们需求。相比之下使用jacob操作word文档非常方便。也比较容易...

ningliuliu的博客 202

SIMATIC S7-1200, S7-1500 PID 控制[手册]

SIMATIC S7-1200, S7-1500 PID 控制[手册]

jacob 操作word 实例

<br />package com.ibm.cmm.app.Utilities; import java.io.File; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant

MaWenWu专栏 1672

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

使用jacob操作word文档

使用jacob要记住用ActiveXComponent调用word的quit方法 1 新建空白的word文档,加入内容,并保存 public class NewAWord{ public NewAWord(){ // 初始化com的线程,非常重要!!使用结束后要调用 release方法 ComThread.InitSTA(); // 初始化word应用程序,...

287

java jacob 操作word 文档,进行写操作,如生成表格,添加 图片

jacob-1.15-M3.zip  jacob-1.15-M3-x86.dll copy 到c:\\windows\system32 引入jacob.jar 示例代码     [java] view plain copy  print? import java.io.File;     importcom.jaco

zzl7412的博客 4273

java使用jacob操作word文档

ava使用jacob操作word文档 java调用com组件操作word使用总结(jacob) 简单描述    在此处输入简单摘要 特别声明:使用java-com技术可以完成任何VBA可以完成的office文档操作;  一、准备工作    先了解一下概念,JACOB 就是 JAVA-COM Bridge的缩写,提供自动化的访问com的功能,也是通

mincheat的专栏 5917
上一篇: flex 导出word
下一篇: flex downLoad
javaee_jsp
博客等级 码龄15年 0粉丝 27原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值