/*
* @(#) WordBean.java Create on 2012-5-17 下午02:58:26
*
* Copyright 2012 by xl.
*/
package cn.tools.word;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
*
* @author zxd
* @date 2012-5-17
*/
public class WordHelper {
private ActiveXComponent MsWordApp = null;
private static final int MAX_RETRY = 10;//取Com接口异常的最多重试次数.
private Dispatch document = null;
public WordHelper() {
if (MsWordApp == null) {
MsWordApp = new ActiveXComponent("Word.Application");
}
}
public void setVisible(boolean visible) {
MsWordApp.setProperty("Visible", new Variant(visible));
}
public void createNewDocument() {
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Add").toDispatch();
}
public void openFile(String wordFilePath) {
// Find the Documents collection object maintained by Word
// documents表示word的所有文档窗口,(word是多文档应用程序)
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Open", wordFilePath,
new Variant(true)/* 是否进行转换ConfirmConversions */,
new Variant(false)/* 是否只读 */).toDispatch();
}
/**
* 插入数据
* @Title: insertText
* @data:2012-5-18上午11:04:07
* @author:zxd
*
* @param textToInsert
*/
public void insertText(String textToInsert) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", textToInsert);
Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));
}
/**
* 插入图片
* @Title: insertJpeg
* @data:2012-5-17下午03:11:22
* @author:zxd
*
* @param jpegFilePath
*/
public void insertJpeg(String jpegFilePath){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
Dispatch.call(image, "AddPicture", jpegFilePath);
}
public void insertFormatContent(String text) {
Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容
Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后
Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs")
.toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(
Variant.VariantInt).getInt();// 一共的段落数
// 找到刚输入的段落,设置格式
Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",
new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)
// Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义
Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range")
.toDispatch();
Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();
Dispatch.put(font, "Bold", new Variant(false)); // 设置为黑体
Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体
Dispatch.put(font, "Name", new Variant("宋体")); //
Dispatch.put(font, "Size", new Variant(9)); // 小四
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.call(selection, "TypeParagraph");// 插入一个空行
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")
.toDispatch();// 段落格式
Dispatch.put(alignment, "Alignment", "3"); // (1:置中 2:靠右 3:靠左)
}
public void listIndent(
final int pos) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch listFormat = Dispatch.get(range, "ListFormat").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(listFormat, "ListIndent");
}
}
/**
* 插入一个换耶夫
* @Title: insertPageBreak
* @data:2012-7-5下午03:46:01
* @author:zxd
*
*/
public void insertPageBreak() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.call(selection, "InsertBreak", new Variant(2));
}
/**
* 插入一段文字.
* @param textToInsert 文字
* @param style 样式
*/
public void insertText(
final String textToInsert,
final String style) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", textToInsert);
Dispatch.put(selection, "Style", getOutlineStyle(style));
Dispatch.call(selection, "MoveRight");
}
public Variant getOutlineStyle(
final String style) {
int index = 1;
while (true) {
try {
return Dispatch.call(
Dispatch.get(document, "Styles").toDispatch(),
"Item", new Variant(style));
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
public void insertFormatStr(String text) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", text);
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体
Dispatch.put(font, "Italic", new Variant(false)); // 设置为斜体
Dispatch.put(font, "Name", new Variant("楷体_GB2312")); //
Dispatch.put(font, "Size", new Variant(12)); // 小四
}
/**
* 插入表格内容
* @Title: insertTable
* @data:2012-5-18上午11:05:50
* @author:zxd
*
* @param tableTitle
* @param row
* @param column
*/
// word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell
// 另外下标从1开始
public void createTable(String pos, int numCols, int numRows) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
if (find(pos)) {
Dispatch tables = Dispatch.get(document, "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, "Right");
}else{
Dispatch tables = Dispatch.get(document, "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");
}
}
/**
* 在指定单元格中填写数据
* @Title: putTxtToCell
* @data:2012-5-17下午04:39:38
* @author:zxd
*
* @param table
* @param cellRowIdx
* @param CellColIdx
* @param text
*/
public void putTxtToCell(Dispatch table,int cellRowIdx,int CellColIdx,String text){
Dispatch cell = Dispatch.call(table, "Cell",new Variant(cellRowIdx), new Variant(CellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", text);//往里面写入数据
}
/**
* 在指定单元格里面填写数据
* @Title: putTxtToCell
* @data:2012-5-17下午05:22:16
* @author:zxd
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
String txt){
//获取所有表格
Dispatch tables = Dispatch.get(document, "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 selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "text", txt);
}
/**
* 往单元格里面填充图片
* @Title: putTxtToImg
* @data:2012-6-29下午03:51:34
* @author:zxd
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToImg(int tableIndex,int cellRowIdx,int cellColIdx,String jpegFilePath){
//获取所有表格
Dispatch tables = Dispatch.get(document, "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 selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
Dispatch.call(image, "AddPicture", jpegFilePath);
}
/**
* 合并连个单元格
* @Title: mergeCell
* @data:2012-5-18上午10:15:17
* @author:zxd
*
* @param cell1
* @param cell2
*/
public void mergeCell(Dispatch cell1, Dispatch cell2){
Dispatch.call(cell1, "Merge",cell2);
}
/**
* 合并两个单元格
* @Title: mergeCell
* @data:2012-5-18上午10:17:03
* @author:zxd
*
* @param table
* @param row1
* @param col1
* @param row2
* @param col2
*/
public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
int secCellRowIdx, int secCellColIdx) {
// 所有表格
Dispatch tables = Dispatch.get(document, "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 pos
* 移动的距离
*/
public void moveUp(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveUp");
}
}
/**
* 向下移动
* @Title: moveDown
* @data:2012-6-29下午02:56:14
* @author:zxd
*
* @param pos
*/
public void moveDown(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveDown");
}
}
public void moveRight(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveRight");
}
}
/**
* 查找文本
* @Title: find
* @data:2012-5-18上午10:28:44
* @author:zxd
*
* @param toFindText
* @return
*/
public boolean find(String toFindText){
if (toFindText == null || toFindText.equals(""))
return false;
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
// 从selection所在位置开始查询
Dispatch find = Dispatch.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toFindText);
// 向前查找
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
return Dispatch.call(find, "Execute").getBoolean();
}
/**
* 把选 定的内容设为替换的内容
* @Title: replaceText
* @data:2012-5-18上午10:29:37
* @author:zxd
*
* @param toFindText
* @param newText
* @return
*/
public boolean replaceText(String toFindText, String newText){
if(!find(toFindText)){
return false;
}
else{
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();//输入内容的对象
Dispatch.put(selection, "Text", newText);
return true;
}
}
/**
* 保存文档内容
* @Title: save
* @data:2012-5-18上午10:32:55
* @author:zxd
*
*/
public void save() {
Dispatch.get(document, "Save");
}
/**
* 保存文件
* @Title: saveFiles
* @data:2012-5-18上午10:34:04
* @author:zxd
*
* @param filename
*/
public void saveFiles(String filename){
Dispatch.call(document, "Save");
}
/**
* 另存为
* @Title: saveFilesAs
* @data:2012-5-18上午10:38:00
* @author:zxd
*
* @param filename
*/
public void saveFilesAs(String filename){
Dispatch.call(document, "SaveAs",filename);
}
/**
* 关闭文件
* @Title: closeDocument
* @data:2012-5-18上午10:40:45
* @author:zxd
*
*/
public void closeDocument(){
Dispatch.call(document, "Close",new Variant(0));
}
/**
* 关闭word
* @Title: closeWord
* @data:2012-5-18上午10:42:10
* @author:zxd
*
*/
public void closeWord(){
Dispatch.call(MsWordApp, "Quit");
MsWordApp = null;
document = null;
}
/**
* 设置word打开后的位置
* @Title: setLocation
* @data:2012-5-18上午10:43:04
* @author:zxd
*
*/
public void setLocation(){
Dispatch actWindow = Dispatch.get(MsWordApp, "Application").toDispatch();//得到当前位置
Dispatch.put(actWindow, "WindowState", new Variant(1));
// 1=maximize
// 2=minimize
Dispatch.put(actWindow, "Top", new Variant(0));
Dispatch.put(actWindow, "Left", new Variant(0));
Dispatch.put(actWindow, "Height", new Variant(600));
Dispatch.put(actWindow, "width", new Variant(800));
}
public void setSeekView(String seekView) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if(seekView != null && !"".equals(seekView)){
//取得活动窗体对象
Dispatch ActiveWindow = MsWordApp.getProperty("ActiveWindow").toDispatch();
//取得活动窗格对象
Dispatch ActivePane = Dispatch.get(ActiveWindow,"ActivePane").toDispatch();
//取得视窗对象
Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
try{
Dispatch.put(View,"SeekView", "9"); //设置页眉
Dispatch.call(selection, "TypeParagraph");
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")
.toDispatch();// 段落格式
Dispatch.put(alignment, "Alignment", 2); // (1:置中 2:靠右 3:靠左)
moveDown(1);
Dispatch.put(selection,"Text",seekView);
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font,"Size", new Variant(9));
Dispatch.call(selection,"MoveRight",new Variant(1),new Variant(1));
Dispatch.put(View, "SeekView", "10"); // 10是设置页脚
}finally{
if(ActiveWindow != null ) ActiveWindow.safeRelease();
if(ActivePane != null ) ActivePane.safeRelease();
if(View != null ) View.safeRelease();
}
}
}
public String theOtherFindText(String value){
//shapes集合
Dispatch shapes = Dispatch.get(document, "Shapes").toDispatch();
//shape的个数
String Count=Dispatch.get(shapes, "Count").toString();
int counts=Integer.parseInt(Count);
for(int i=1;i<=counts;i++){ //Item 下标从1 开始
//取得一个shape
Dispatch shape=Dispatch.call(shapes, "Item",new Variant(i)).toDispatch();
Dispatch textframe=Dispatch.get(shape, "TextFrame").toDispatch();
boolean hasText=Dispatch.call(textframe, "HasText").toBoolean();
if(hasText){
Dispatch TextRange=Dispatch.get(textframe, "TextRange").toDispatch();
String str=Dispatch.get(TextRange, "Text").toString();
Dispatch.put(TextRange, "Text",value); //替换内容
}
}
return "";
}
/**
* 将文件移动到首位置
* @Title: moveStart
* @data:2012-6-29上午11:51:25
* @author:zxd
*
*/
public void moveStart() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if (selection == null)
selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 查找文本,并且替换
* @Title: replaceAllText
* @data:2012-6-29下午02:51:18
* @author:zxd
*
* @param toFindText
* @param newText
*/
public void replaceAllText(String toFindText, String newText) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
while (find(toFindText)) {
Dispatch.put(selection, "Text", newText);
Dispatch.call(selection, "MoveRight");
}
}
public void insertToc()
{
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
Dispatch range = Dispatch.get(selection, "RANGE").toDispatch();
Dispatch fields = Dispatch.call(selection, "FIELDS").toDispatch();
Dispatch.call(fields,"ADD",range,new Variant(-1), new Variant("TOC \\h "), new Variant(false));
}
/**
* 回车换行
* @Title: enter
* @data:2012-7-2上午10:45:36
* @author:zxd
*
*/
public void enter() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
int index = 1;
while (true) {
try {
Dispatch.call(selection,"TypeParagraph");
break;
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
public void insertHylinks(String pageUrl){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
Dispatch Hyperlinks = Dispatch.get(document,"Hyperlinks").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch h=Dispatch.invoke(
Hyperlinks,"Add", Dispatch.Method,
new Object[]{ range,new Variant(pageUrl)},new int[1]).toDispatch();
Dispatch hRange=Dispatch.get(h, "Range").toDispatch();
Dispatch.call(hRange,"select");
Dispatch.call(selection,"MoveRight",new Variant(1),new Variant(1));
}
/**
* 光标移到末尾
* @Title: moveEnd
* @data:2012-7-5下午05:32:14
* @author:zxd
*
*/
public void moveEnd() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if (selection == null) {
selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
}
Dispatch.call(selection, "EndKey", new Variant(6));
}
}
* @(#) WordBean.java Create on 2012-5-17 下午02:58:26
*
* Copyright 2012 by xl.
*/
package cn.tools.word;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
*
* @author zxd
* @date 2012-5-17
*/
public class WordHelper {
private ActiveXComponent MsWordApp = null;
private static final int MAX_RETRY = 10;//取Com接口异常的最多重试次数.
private Dispatch document = null;
public WordHelper() {
if (MsWordApp == null) {
MsWordApp = new ActiveXComponent("Word.Application");
}
}
public void setVisible(boolean visible) {
MsWordApp.setProperty("Visible", new Variant(visible));
}
public void createNewDocument() {
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Add").toDispatch();
}
public void openFile(String wordFilePath) {
// Find the Documents collection object maintained by Word
// documents表示word的所有文档窗口,(word是多文档应用程序)
Dispatch documents = Dispatch.get(MsWordApp, "Documents").toDispatch();
document = Dispatch.call(documents, "Open", wordFilePath,
new Variant(true)/* 是否进行转换ConfirmConversions */,
new Variant(false)/* 是否只读 */).toDispatch();
}
/**
* 插入数据
* @Title: insertText
* @data:2012-5-18上午11:04:07
* @author:zxd
*
* @param textToInsert
*/
public void insertText(String textToInsert) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", textToInsert);
Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));
}
/**
* 插入图片
* @Title: insertJpeg
* @data:2012-5-17下午03:11:22
* @author:zxd
*
* @param jpegFilePath
*/
public void insertJpeg(String jpegFilePath){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
Dispatch.call(image, "AddPicture", jpegFilePath);
}
public void insertFormatContent(String text) {
Dispatch wordContent = Dispatch.get(document, "Content").toDispatch(); // 取得word文件的内容
Dispatch.call(wordContent, "InsertAfter", text);// 插入一个段落到最后
Dispatch paragraphs = Dispatch.get(wordContent, "Paragraphs")
.toDispatch(); // 所有段落
int paragraphCount = Dispatch.get(paragraphs, "Count").changeType(
Variant.VariantInt).getInt();// 一共的段落数
// 找到刚输入的段落,设置格式
Dispatch lastParagraph = Dispatch.call(paragraphs, "Item",
new Variant(paragraphCount)).toDispatch(); // 最后一段(也就是刚插入的)
// Range 对象表示文档中的一个连续范围,由一个起始字符位置和一个终止字符位置定义
Dispatch lastParagraphRange = Dispatch.get(lastParagraph, "Range")
.toDispatch();
Dispatch font = Dispatch.get(lastParagraphRange, "Font").toDispatch();
Dispatch.put(font, "Bold", new Variant(false)); // 设置为黑体
Dispatch.put(font, "Italic", new Variant(true)); // 设置为斜体
Dispatch.put(font, "Name", new Variant("宋体")); //
Dispatch.put(font, "Size", new Variant(9)); // 小四
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.call(selection, "TypeParagraph");// 插入一个空行
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")
.toDispatch();// 段落格式
Dispatch.put(alignment, "Alignment", "3"); // (1:置中 2:靠右 3:靠左)
}
public void listIndent(
final int pos) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch listFormat = Dispatch.get(range, "ListFormat").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(listFormat, "ListIndent");
}
}
/**
* 插入一个换耶夫
* @Title: insertPageBreak
* @data:2012-7-5下午03:46:01
* @author:zxd
*
*/
public void insertPageBreak() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.call(selection, "InsertBreak", new Variant(2));
}
/**
* 插入一段文字.
* @param textToInsert 文字
* @param style 样式
*/
public void insertText(
final String textToInsert,
final String style) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", textToInsert);
Dispatch.put(selection, "Style", getOutlineStyle(style));
Dispatch.call(selection, "MoveRight");
}
public Variant getOutlineStyle(
final String style) {
int index = 1;
while (true) {
try {
return Dispatch.call(
Dispatch.get(document, "Styles").toDispatch(),
"Item", new Variant(style));
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
public void insertFormatStr(String text) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", text);
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font, "Bold", new Variant(true)); // 设置为黑体
Dispatch.put(font, "Italic", new Variant(false)); // 设置为斜体
Dispatch.put(font, "Name", new Variant("楷体_GB2312")); //
Dispatch.put(font, "Size", new Variant(12)); // 小四
}
/**
* 插入表格内容
* @Title: insertTable
* @data:2012-5-18上午11:05:50
* @author:zxd
*
* @param tableTitle
* @param row
* @param column
*/
// word 中在对表格进行遍历的时候 ,是先列后行 先column 后cell
// 另外下标从1开始
public void createTable(String pos, int numCols, int numRows) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
if (find(pos)) {
Dispatch tables = Dispatch.get(document, "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, "Right");
}else{
Dispatch tables = Dispatch.get(document, "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");
}
}
/**
* 在指定单元格中填写数据
* @Title: putTxtToCell
* @data:2012-5-17下午04:39:38
* @author:zxd
*
* @param table
* @param cellRowIdx
* @param CellColIdx
* @param text
*/
public void putTxtToCell(Dispatch table,int cellRowIdx,int CellColIdx,String text){
Dispatch cell = Dispatch.call(table, "Cell",new Variant(cellRowIdx), new Variant(CellColIdx)).toDispatch();
Dispatch.call(cell, "Select");
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "Text", text);//往里面写入数据
}
/**
* 在指定单元格里面填写数据
* @Title: putTxtToCell
* @data:2012-5-17下午05:22:16
* @author:zxd
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToCell(int tableIndex, int cellRowIdx, int cellColIdx,
String txt){
//获取所有表格
Dispatch tables = Dispatch.get(document, "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 selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.put(selection, "text", txt);
}
/**
* 往单元格里面填充图片
* @Title: putTxtToImg
* @data:2012-6-29下午03:51:34
* @author:zxd
*
* @param tableIndex
* @param cellRowIdx
* @param cellColIdx
* @param txt
*/
public void putTxtToImg(int tableIndex,int cellRowIdx,int cellColIdx,String jpegFilePath){
//获取所有表格
Dispatch tables = Dispatch.get(document, "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 selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch image = Dispatch.get(selection, "InLineShapes").toDispatch();
Dispatch.call(image, "AddPicture", jpegFilePath);
}
/**
* 合并连个单元格
* @Title: mergeCell
* @data:2012-5-18上午10:15:17
* @author:zxd
*
* @param cell1
* @param cell2
*/
public void mergeCell(Dispatch cell1, Dispatch cell2){
Dispatch.call(cell1, "Merge",cell2);
}
/**
* 合并两个单元格
* @Title: mergeCell
* @data:2012-5-18上午10:17:03
* @author:zxd
*
* @param table
* @param row1
* @param col1
* @param row2
* @param col2
*/
public void mergeCell(int tableIndex, int fstCellRowIdx, int fstCellColIdx,
int secCellRowIdx, int secCellColIdx) {
// 所有表格
Dispatch tables = Dispatch.get(document, "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 pos
* 移动的距离
*/
public void moveUp(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveUp");
}
}
/**
* 向下移动
* @Title: moveDown
* @data:2012-6-29下午02:56:14
* @author:zxd
*
* @param pos
*/
public void moveDown(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveDown");
}
}
public void moveRight(int pos){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
for (int i = 0; i < pos; i++) {
Dispatch.call(selection, "MoveRight");
}
}
/**
* 查找文本
* @Title: find
* @data:2012-5-18上午10:28:44
* @author:zxd
*
* @param toFindText
* @return
*/
public boolean find(String toFindText){
if (toFindText == null || toFindText.equals(""))
return false;
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
// 从selection所在位置开始查询
Dispatch find = Dispatch.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toFindText);
// 向前查找
Dispatch.put(find, "MatchWholeWord", "True");
// 查找并选中
return Dispatch.call(find, "Execute").getBoolean();
}
/**
* 把选 定的内容设为替换的内容
* @Title: replaceText
* @data:2012-5-18上午10:29:37
* @author:zxd
*
* @param toFindText
* @param newText
* @return
*/
public boolean replaceText(String toFindText, String newText){
if(!find(toFindText)){
return false;
}
else{
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch();//输入内容的对象
Dispatch.put(selection, "Text", newText);
return true;
}
}
/**
* 保存文档内容
* @Title: save
* @data:2012-5-18上午10:32:55
* @author:zxd
*
*/
public void save() {
Dispatch.get(document, "Save");
}
/**
* 保存文件
* @Title: saveFiles
* @data:2012-5-18上午10:34:04
* @author:zxd
*
* @param filename
*/
public void saveFiles(String filename){
Dispatch.call(document, "Save");
}
/**
* 另存为
* @Title: saveFilesAs
* @data:2012-5-18上午10:38:00
* @author:zxd
*
* @param filename
*/
public void saveFilesAs(String filename){
Dispatch.call(document, "SaveAs",filename);
}
/**
* 关闭文件
* @Title: closeDocument
* @data:2012-5-18上午10:40:45
* @author:zxd
*
*/
public void closeDocument(){
Dispatch.call(document, "Close",new Variant(0));
}
/**
* 关闭word
* @Title: closeWord
* @data:2012-5-18上午10:42:10
* @author:zxd
*
*/
public void closeWord(){
Dispatch.call(MsWordApp, "Quit");
MsWordApp = null;
document = null;
}
/**
* 设置word打开后的位置
* @Title: setLocation
* @data:2012-5-18上午10:43:04
* @author:zxd
*
*/
public void setLocation(){
Dispatch actWindow = Dispatch.get(MsWordApp, "Application").toDispatch();//得到当前位置
Dispatch.put(actWindow, "WindowState", new Variant(1));
// 1=maximize
// 2=minimize
Dispatch.put(actWindow, "Top", new Variant(0));
Dispatch.put(actWindow, "Left", new Variant(0));
Dispatch.put(actWindow, "Height", new Variant(600));
Dispatch.put(actWindow, "width", new Variant(800));
}
public void setSeekView(String seekView) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if(seekView != null && !"".equals(seekView)){
//取得活动窗体对象
Dispatch ActiveWindow = MsWordApp.getProperty("ActiveWindow").toDispatch();
//取得活动窗格对象
Dispatch ActivePane = Dispatch.get(ActiveWindow,"ActivePane").toDispatch();
//取得视窗对象
Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
try{
Dispatch.put(View,"SeekView", "9"); //设置页眉
Dispatch.call(selection, "TypeParagraph");
Dispatch alignment = Dispatch.get(selection, "ParagraphFormat")
.toDispatch();// 段落格式
Dispatch.put(alignment, "Alignment", 2); // (1:置中 2:靠右 3:靠左)
moveDown(1);
Dispatch.put(selection,"Text",seekView);
Dispatch font = Dispatch.get(selection, "Font").toDispatch();
Dispatch.put(font,"Size", new Variant(9));
Dispatch.call(selection,"MoveRight",new Variant(1),new Variant(1));
Dispatch.put(View, "SeekView", "10"); // 10是设置页脚
}finally{
if(ActiveWindow != null ) ActiveWindow.safeRelease();
if(ActivePane != null ) ActivePane.safeRelease();
if(View != null ) View.safeRelease();
}
}
}
public String theOtherFindText(String value){
//shapes集合
Dispatch shapes = Dispatch.get(document, "Shapes").toDispatch();
//shape的个数
String Count=Dispatch.get(shapes, "Count").toString();
int counts=Integer.parseInt(Count);
for(int i=1;i<=counts;i++){ //Item 下标从1 开始
//取得一个shape
Dispatch shape=Dispatch.call(shapes, "Item",new Variant(i)).toDispatch();
Dispatch textframe=Dispatch.get(shape, "TextFrame").toDispatch();
boolean hasText=Dispatch.call(textframe, "HasText").toBoolean();
if(hasText){
Dispatch TextRange=Dispatch.get(textframe, "TextRange").toDispatch();
String str=Dispatch.get(TextRange, "Text").toString();
Dispatch.put(TextRange, "Text",value); //替换内容
}
}
return "";
}
/**
* 将文件移动到首位置
* @Title: moveStart
* @data:2012-6-29上午11:51:25
* @author:zxd
*
*/
public void moveStart() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if (selection == null)
selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
Dispatch.call(selection, "HomeKey", new Variant(6));
}
/**
* 查找文本,并且替换
* @Title: replaceAllText
* @data:2012-6-29下午02:51:18
* @author:zxd
*
* @param toFindText
* @param newText
*/
public void replaceAllText(String toFindText, String newText) {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
while (find(toFindText)) {
Dispatch.put(selection, "Text", newText);
Dispatch.call(selection, "MoveRight");
}
}
public void insertToc()
{
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
Dispatch range = Dispatch.get(selection, "RANGE").toDispatch();
Dispatch fields = Dispatch.call(selection, "FIELDS").toDispatch();
Dispatch.call(fields,"ADD",range,new Variant(-1), new Variant("TOC \\h "), new Variant(false));
}
/**
* 回车换行
* @Title: enter
* @data:2012-7-2上午10:45:36
* @author:zxd
*
*/
public void enter() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
int index = 1;
while (true) {
try {
Dispatch.call(selection,"TypeParagraph");
break;
} catch (ComFailException e) {
if (index++ >= MAX_RETRY) {
throw e;
} else {
continue;
}
}
}
}
public void insertHylinks(String pageUrl){
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
Dispatch Hyperlinks = Dispatch.get(document,"Hyperlinks").toDispatch();
Dispatch range = Dispatch.get(selection, "Range").toDispatch();
Dispatch h=Dispatch.invoke(
Hyperlinks,"Add", Dispatch.Method,
new Object[]{ range,new Variant(pageUrl)},new int[1]).toDispatch();
Dispatch hRange=Dispatch.get(h, "Range").toDispatch();
Dispatch.call(hRange,"select");
Dispatch.call(selection,"MoveRight",new Variant(1),new Variant(1));
}
/**
* 光标移到末尾
* @Title: moveEnd
* @data:2012-7-5下午05:32:14
* @author:zxd
*
*/
public void moveEnd() {
Dispatch selection = Dispatch.get(MsWordApp, "Selection").toDispatch(); // 输入内容需要的对象
if (selection == null) {
selection = Dispatch.get(MsWordApp, "Selection").toDispatch();
}
Dispatch.call(selection, "EndKey", new Variant(6));
}
}
评论
1 楼
贝塔ZQ
2016-09-27
Jacob操作word代码量好大啊,建议楼主用插件试试看,还省事儿,用PageOffice插件试试,操作office文件简单方便,功能强大还,集成起来也方便,就几行代码的事儿。
相关推荐
本文将详细讲解如何使用Java操作Word,特别是针对书签插值的方法,以及相关的技术和工具。 1. **Java操作Word的基本原理** Java操作Word主要依赖于第三方库,如Apache POI和JACOB。Apache POI是一个用于读写...
Java 操作Excel和Word的所有资料Java 操作Excel和Word的所有资料Java 操作Excel和Word的所有资料Java 操作Excel和Word的所有资料Java 操作Excel和Word的所有资料Java 操作Excel和Word的所有资料Java 操作Excel和Word...
Java 操作 Word 文档,尤其是处理书签,是一种常见的需求,尤其在自动化报告生成或文档模板填充场景中。本文将详细介绍如何使用 Java 实现这一功能,避免依赖第三方库,如 Apache POI、java2word 或 jcob。 首先,...
在“使用Aspose.Words for Java完成复杂Word与PDF的导出”这个主题中,我们可以深入探讨以下几个关键知识点: 1. **Aspose.Words for Java的安装与集成**:首先,你需要将Aspose.Words库引入到Java项目中,这通常...
java操作word 实现了三个功能:模板填充,模板数据提取,格式颜色验证,具体解压jar包WordTest实例,注意针对word2007以上,书签要对应
通过Java2Word,开发者可以利用Java代码来创建、填充模板、格式化文本、插入图片、表格等,生成复杂的Word文档。 2. **生成Word文档**: 要使用Java2Word生成Word文档,首先需要创建一个`Document`对象,然后添加...
Java操作Word文件主要涉及到的是对Microsoft Office文档的处理,这在很多企业级应用中非常常见,比如自动化报告生成、数据导入导出等。在Java中,由于Java本身并不直接支持与Windows API交互,因此需要借助第三方库...
总结起来,Java操作Word文档主要依赖于像Jacob这样的第三方库,它提供了与Windows COM接口交互的能力。通过正确配置库文件和遵循上述步骤,开发者可以在Java程序中实现对Word文档的各种复杂操作。
同样,iText主要用于PDF和Excel操作,而非复杂的Word文档生成。 直接通过JSP来输出Word文档样式往往难以满足打印质量的要求,因为JSP更适合动态生成HTML页面,而无法很好地模拟Word的样式和排版规则。 一个创新的...
在这个场景中,我们将重点讨论如何使用Java POI来操作Word模板文件,生成表单以及进行修改,特别是处理含有下拉框等交互元素的情况。 首先,让我们了解Java POI的基本用法。要操作Word文档,我们需要导入`org....
以上就是使用Java通过jacob库操作Word文档的基本步骤和关键知识点。在实际开发中,根据具体需求可以进一步扩展和优化此类,以实现更复杂的功能。同时,需要注意的是,由于jacob依赖于特定的操作系统和Office版本,...
Java使用FTL(FreeMarker Template Language)模板生成多表格复杂性Word文档是一项常见的技术需求,尤其是在需要自动生成报告或批量处理文档的场景中。FreeMarker是一个强大的、基于模板的Java库,它允许开发者将...
这个例子只是一个起点,实际的HTML到Word转换过程会更复杂,需要处理HTML标签、CSS样式、图像等内容。可能还需要考虑HTML的嵌套结构,以及如何将它们映射到Word的段落、列表、表格等元素。此外,Apache POI不支持...
通过以上介绍,我们可以看出Java操作Word的POI库功能强大,不仅可以创建新文档,还能读取、修改现有文档,甚至处理复杂的格式如表格和样式。学习和掌握POI,对于进行Java相关的文档处理工作是非常有价值的。
在本例中,Jacob是连接Java和Microsoft Office的桥梁,使得Java代码能够操作Word对象模型,创建、修改Word文档。Jacob提供了一种方式来与Word交互,如打开、修改、保存和创建新的Word文档。 `Java2Word.jar`则是...
Java 生成复杂 Word 文档存在许多难点,例如 POI 读写 Word 文档的限制、iText 操作 Excel 的局限性、直接通过 JSP 输出样式的不达标等。这些难点使得生成复杂 Word 文档变得非常困难。 知识点2: 使用 Office 2003 ...
它基于XML,允许开发者创建复杂的Word文档,包括段落、表格、图片等。 3. **HSSF (Horrible Spreadsheet Format):** 虽然不是直接与Word相关,但HSSF是Apache POI处理老版本Word(.doc)文档的组件。如果需要处理旧...
在Java开发中,生成Word文档是一项常见的需求,特别是在企业级应用中,如报告生成、合同制作等。"Java通过word模板配置书签生成word"是一个...因此,理解如何在Java中操作Word模板和书签是提高效率和代码质量的关键。
Java POI 操作 Word 是一个高效且广泛使用的技术,它允许开发者在 Java 应用程序中创建、修改和读取 Microsoft Word 文档。相对于其他如 Jacob 的解决方案,POI 提供了更高的性能,并且它的API更为简洁易用。在本文...