java jacob word

来源:互联网 发布:华中数控车床仿真软件 编辑:程序博客网 时间:2024/05/22 10:42


里面的内容网上有很多,我弄过来改的,也加了些小东东,以备后用。里面的内容,当时不知是从哪个牛兄那里拿过来的,

先谢过了。

1 页眉的处理,里面有,看到网上也是这么弄的,但我是没有试出来。

2 对于字体的设置,除了在表格里面的管用,别的地方不知道为啥不管用了。

3 对于页眉的处理,本来打算是页眉中有text文本框的,以为可以进行用文本框进行处理,

  后来发现遍历所有的文本框的时候,根本不会遍历到页眉中的文本框。 

  解决办法:直接将页眉中的文本框给踢掉了,在页眉上面加了个文本框,设置成100%透明,边框无色的,无奈地办法呵呵

4 下面的代码是在项目中拎出来的,可以直接用哦

/*
 * 传入数据为HashMap对象,对象中的Key代表word模板中要替换的字段,Value代表用来替换的值。
 * word模板中所有要替换的字段(即HashMap中的Key)以特殊字符开头和结尾, 如:$code$、$date$……, 以免执行错误的替换。
 * 
 * 所有要替换为图片的字段,Key中需包含image或者Value为图片的全路径(目前只判断文件后缀名为:.bmp、 .jpg、.gif)。
 * 
 * 要替换表格中的数据时,HashMap中的Key格式为“table$R@N”,其中:R代表从表格的第R行开始替换,N代表
 * word模板中的第N张表格;Value为ArrayList对象,ArrayList中包含的对象统一为String[],一条String[]代
 * 表一行数据,ArrayList中第一条记录为特殊记录,记录的是表格中要替换的列号,如:要替换第一列、第三列、
 * 第五列的数据,则第一条记录为String[3] {“1”,”3”,”5”}。
 */


/**
 * 1 增加目标文件的删除
 * 2 对文本框中的内容的替换操作 2011年11月14日
 *   map.put("TextFrame$tradday$","2011-11-12");
 *
 */


import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;


import cn.com.inxite.util.DatetimeUtil;
import cn.com.inxite.util.GlobalVarUtil;
import cn.com.inxite.util.Utils;


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




public class Java2Word_Jacob {

//
/**

*/
private static final Java2Word_Jacob instance = null;


private boolean saveOnExit;
/**
* word文档
*/
Dispatch doc = null;


/**
* word运行程序对象s
*/
private ActiveXComponent word;
/**
* 所有word文档
*/
private Dispatch documents;
//
/**
*  选定
*/
Dispatch selection;


/**
* 构造函数
*/
public Java2Word_Jacob() {
if (word == null) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(false));
word.setProperty("AutomationSecurity", new Variant(3)); //禁用宏  
}
if (documents == null)
documents = word.getProperty("Documents").toDispatch();

// 初始化com的线程,使用结束后要调用realease方法,见quit函数
        ComThread.InitSTA();
saveOnExit = false;
}
//
/**

* get Java2Word_Jacob instance
* @return
* @author lizx 
*    Nov 12, 2011 3:46:39 PM
*/
public static Java2Word_Jacob getInstance(){
if(instance == null)
return new Java2Word_Jacob();
return instance;
}


/**
* 设置参数:退出时是否保存

* @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 toText) {
// 从selection所在位置开始查询
Dispatch find = word.call(selection, "Find").toDispatch();
// 设置要查找的内容
Dispatch.put(find, "Text", toText);
// 向前查找
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 if (oldText.startsWith("pageHeader")){
setPageHeader(selection, (String)replaceObj);
}
//文本框内容替换
else if (oldText.indexOf("TextFrame")>-1){
textFrameoper(oldText,(String)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();
Dispatch colums = Dispatch.get(table, "Columns").toDispatch();
// 填充表格
for (int i = 1; i < dataList.size(); i++) {
// 某一行数据
String[] datas = (String[]) dataList.get(i);


// 在表格中添加一行
int rowcount = Dispatch.get(rows, "Count").getInt();
int columscount = Dispatch.get(colums, "Count").getInt();
if (rowcount < fromRow + i)
Dispatch.call(rows, "Add");
// System.out.println("rowcount=="+rowcount + "
// columscount="+columscount);


Dispatch row = Dispatch.invoke(rows, "item", Dispatch.Method,
new Object[] { new Integer(rowcount + 1) }, new int[1])
.toDispatch();
// 填充该行的相关列
for (int j = 0; j < datas.length; j++) {


// 得到单元格
Dispatch cell = Dispatch.call(table, "Cell",
Integer.toString(fromRow + i), 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(font, "Color", "0,0,0");
// 输入数据
Dispatch.put(selection, "Text", datas[j]);


// 设置当前行背景色 无色
Dispatch shading = Dispatch.get(row, "Shading").toDispatch();
Dispatch.put(shading, "BackgroundPatternColorIndex",
new Variant(0));
}
}
}


/**
* 保存文件

* @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, Map data) {
String oldText;
Object newValue;
try {
if (doc == null)
doc = open(inputPath);
delFile(outPath);


   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);

ComThread.Release();
}
}


//
/**
* 先删除目标file

* @param filepath
* @throws Exception
* @author lizx Nov 12, 2011 2:30:39 PM
*/
public void delFile(String filepath) throws Exception {
File file = new File(filepath);
if (file != null && file.exists()) {
file.delete();
System.out.println(filepath + "  delted!");
}
}


//
/**
* 设置页眉

* @param text
* @author lizx Nov 12, 2011 3:35:58 PM
*/
public void setPageHeader(Dispatch selecttion,String text) {
// Dispatch ActiveWindow = word.getProperty("ActiveWindow")
// .toDispatch();
// // 取得活动窗格对象
// Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane")
// .toDispatch();
// // 取得视窗对象
// Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
//
// /** **设置页眉**** */
// Dispatch.put(View, "SeekView", "9");
// Dispatch.put(selecttion, "Text", text);
//


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(text));   
        //String content = Dispatch.get(range, "Text").toString();  
        Dispatch font = Dispatch.get(range, "Font").toDispatch();  
          
        Dispatch.put(font, "Name", new Variant("楷体_GB2312"));  
        Dispatch.put(font, "Bold", new Variant(true));  
        //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));   
}

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


    //
    /**
     * 文本框文本处理
     * @param key
     * @param value
     * @author lizx 
     *    Nov 14, 2011 11:23:20 AM
     */
    public void textFrameoper (String key,String value){
    Dispatch shapes = Dispatch.get(doc, "Shapes").toDispatch(); //shapes集合 
    String Count=Dispatch.get(shapes, "Count").toString(); //shape的个数 
    for(int i=1;i<= Integer.parseInt(Count);i++){ //Item 下标从1 开始 
    Dispatch shape=Dispatch.call(shapes, "Item",new Variant(i)).toDispatch(); //取得一个shape 
    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();
      //     System.out.println("key="+key + " str="+str);
//         System.out.println(key.equals(str+"\r"));
        if(! Utils.strIsNull(str) && str.indexOf(key) > -1){
        Dispatch.put(TextRange, "Text",value); //替换内容 
        }
       
    }
    }
    }
    /** 
     * 设置当前选定内容的字体 
     *  
     * @param boldSize 
     * @param italicSize 
     * @param underLineSize 
     *            下划线 
     * @param colorSize 
     *            字体颜色 
     * @param size 
     *            字体大小 
     * @param name 
     *            字体名称 
     */  
    public void setFont(boolean bold, boolean italic, boolean underLine,  
      String colorSize, 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, "Color", colorSize);  
     Dispatch.put(font, "Size", size);  
    }    
    
public synchronized static void word(String inputPath, String outPath,
Map data) {
Java2Word_Jacob j2w = getInstance();
j2w.toWord(inputPath, outPath, data);
}


public static void main(String[] args) {
LinkedHashMap data = new LinkedHashMap();
   Date now = new Date();
data.put("pageHeader", "9999999999999921aswo我的的joe就地方111");
data.put("$TextFramepubdate$", DatetimeUtil.fmtDate(now, DatetimeUtil.DATE_PATTERN_EEE));
data.put("$TextFrameHeader$", DatetimeUtil.fmtDate(now, DatetimeUtil.DATE_PATTERN_EEE)  + "   研究所");
data.put("$TextFrametoday$", DatetimeUtil.fmtDate(new Date(), DatetimeUtil.DATE_PATTERN_CH));

ArrayList table = new ArrayList();
String[] fieldName = new String[] { "1", "2", "3", "4", "5", "6" };
String[] field1 = new String[] { "600000", "浦发银行", "买入", "20000",
"abc", "2011-11-10" };
String[] field2 = new String[] { "600000", "浦发银行", "买入", "20000",
"abc", "2011-11-10" };


table.add(fieldName);
table.add(field1);
table.add(field2);
data.put("table$2@1", table);

data.put("$Dyconmments$", "abcedfeesf我的测温时是今天的股市有点过山车啊");
data.put("$imageinsert$", "D:\\TEST.jpg");//有顺序的


String[] fieldName2 = new String[] { "1", "2", "3", "4", "5", "6", "7",
"8", "9" };
String[] field21 = new String[] { "600000", "浦发银行", "买入", "20000",
"abc", "2011-11-10", "a", "b", "c" };
String[] field22 = new String[] { "600000", "浦发银行", "买入", "20000",
"abc", "2011-11-10", "a", "b", "c" };
ArrayList table2 = new ArrayList();


table2.add(fieldName2);
table2.add(field21);
table2.add(field22);
data.put("table$2@3", table2);


String[] fieldName3 = new String[] { "1", "2", "3" };
String[] field31 = new String[] { "600000", "浦发银行", "买入" };
String[] field32 = new String[] { "600000", "浦发银行", "买入" };
ArrayList table3 = new ArrayList();


table3.add(fieldName3);
table3.add(field31);
table3.add(field32);
data.put("table$2@5", table3);


Java2Word_Jacob j2w = getInstance();
long time1 = System.currentTimeMillis();
j2w.word("D:\\template\\abc.doc", "D:\\result.doc", data);
System.out.println("time cost : "
+ (System.currentTimeMillis() - time1));
}


public static void Java2Word(String inputPath, String outPath, Map data) {
long time1 = System.currentTimeMillis();
Java2Word_Jacob j2w = getInstance();
j2w.word(inputPath, outPath, data);
System.out.println("time cost : "
+ (System.currentTimeMillis() - time1));
}


}