项目开发过程中,需求涉及到了各种文档转换为HTML或者网页易显示格式,现在将实现方式整理如下:
一、了解Jacob
先了解一下概念,JACOB 就是 JAVA-COM Bridge的缩写,提供自动化的访问com的功能,也是通过JNI功能访问windows平台下的com组件或者win32系统库的。这是一个开始于1999年的开源项目的成果,有很多使用者对该项目进行了修改,做出了自己的贡献。
下载地址:http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368
二、Jacob安装
1、我们解开下载的jacob_1.9.zip,在文件夹中找到jacob.dll和jacob.jar两个文件
2、将压缩包解压后,Jacob.jar添加到Libraries中;
3、将Jacob.dll放至“WINDOWS\SYSTEM32”下面。
需要注意的是:
【使用IDE启动Web服务器时,系统读取不到Jacob.dll,例如用MyEclipse启动Tomcat,就需要将dll文件copy到MyEclipse安装目录的“jre\bin”下面。
一般系统没有加载到Jacob.dll文件时,报错信息为:“java.lang.UnsatisfiedLinkError: no jacob injava.library.path”】
三、使用Jacob转换Word,Excel为HTML
JAVA代码:
1. import java.io.BufferedReader;
2. import java.io.BufferedWriter;
3. import java.io.File;
4. import java.io.FileInputStream;
5. import java.io.FileNotFoundException;
6. import java.io.FileWriter;
7. import java.io.IOException;
8. import java.io.InputStreamReader;
9.
10.import com.jacob.activeX.ActiveXComponent;
11.import com.jacob.com.Dispatch;
12.import com.jacob.com.Variant;
13.
14.public class TransformFiletoHtml
15.{
16. int WORD_HTML = 8;
17. int WORD_TXT = 7;
18. int EXCEL_HTML = 44;
19.
20. /**
21. * WORD转HTML
22. * @param docfile WORD文件全路径
23. * @param htmlfile 转换后HTML存放路径
24. */
25. public void wordToHtml(String docfile, String htmlfile)
26. {
27. ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
28. try
29. {
30. app.setProperty("Visible", new Variant(false));
31. Dispatch docs = app.getProperty("Documents").toDispatch();
32. Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { docfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch();
33. Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(WORD_HTML) }, new int[1]);
34. Variant f = new Variant(false);
35. Dispatch.call(doc, "Close", f);
36. }
37. catch (Exception e)
38. {
39. e.printStackTrace();
40. }
41. finally
42. {
43. app.invoke("Quit", new Variant[] {});
44. }
45. }
46.
47. /**
48. * EXCEL转HTML
49. * @param xlsfile EXCEL文件全路径
50. * @param htmlfile 转换后HTML存放路径
51. */
52. public void excelToHtml(String xlsfile, String htmlfile)
53. {
54. ActiveXComponent app = new ActiveXComponent("Excel.Application"); // 启动excel
55. try
56. {
57. app.setProperty("Visible", new Variant(false));
58. Dispatch excels = app.getProperty("Workbooks").toDispatch();
59. Dispatch excel = Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[] { xlsfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch();
60. Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(EXCEL_HTML) }, new int[1]);
61. Variant f = new Variant(false);
62. Dispatch.call(excel, "Close", f);
63. }
64. catch (Exception e)
65. {
66. e.printStackTrace();
67. }
68. finally
69. {
70. app.invoke("Quit", new Variant[] {});
71. }
72. }
73.
74. /**
75. * /删除指定文件夹
76. * @param folderPath 文件夹全路径
77. * @param htmlfile 转换后HTML存放路径
78. */
79. public void delFolder(String folderPath)
80. {
81. try
82. {
83. delAllFile(folderPath); //删除完里面所有内容
84. String filePath = folderPath;
85. filePath = filePath.toString();
86. java.io.File myFilePath = new java.io.File(filePath);
87. myFilePath.delete(); //删除空文件夹
88. } catch (Exception e) {e.printStackTrace();}
89. }
90.
91. /**
92. * /删除指定文件夹下所有文件
93. * @param path 文件全路径
94. */
95. public boolean delAllFile(String path)
96. {
97. boolean flag = false;
98. File file = new File(path);
99. if (!file.exists())
100. {
101. return flag;
102. }
103. if (!file.isDirectory())
104. {
105. return flag;
106. }
107. String[] tempList = file.list();
108. File temp = null;
109. for (int i = 0; i < tempList.length; i++)
110. {
111. if (path.endsWith(File.separator))
112. {
113. temp = new File(path + tempList[i]);
114. }
115. else
116. {
117. temp = new File(path + File.separator + tempList[i]);
118. }
119. if (temp.isFile())
120. {
121. temp.delete();
122. }
123. if (temp.isDirectory())
124. {
125. delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件
126. delFolder(path + "/" + tempList[i]);//再删除空文件夹
127. flag = true;
128. }
129. }
130. return flag;
131. }
132. }
调用JAVA代码:
1. public class Test1 {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. TransformFiletoHtml trans = new TransformFiletoHtml();
5. trans.wordToHtml("D:\\sinye.doc", "D:\\sinye.html");
6. }
7.
8. }
只写了一个测试word转html的,excel转html的同理,在TransformFiletoHtml类中,写了两个方法,一个是删除文件夹的方法(delFolder()),一个是删除文件夹下所有文件的方法(delAllFile())。写这个的目的是出于:在word或者excel转html的过程中,除了生成制定的html页面外,jacob组件会生成一些转换html页面时相关的其它页面,但是这些相关的其它页面不是我们所需要的,因此想把它删除,其实不删除也可以,只是看着不爽,在测试中,发现,word有时不会生成这样的文件,而且即使生成了,也能删除掉,但是excel生成的文件却不能删除,还望高手们给予解答。
另外,在你将excel转换html时,如果你的代码没问题,转换时,老提示什么存在用户区域的安全设置这什么的,会让你选择继续转换,还是取消。这是因为你转换的那个excel中写了保护,解决办法是在excel的工具->保护->允许用户编辑区域,删除里面的所有保护。
整体思路参考http://www.iteye.com/topic/588050
上面的这篇文章使用jacob将word转换成HTML的,利用的是Word的另存为功能,在Office 2007 SP2之后,Office就可以另存为PDF了,可以使用这个方法将office另存为PDF文档。
具体代码可以参考上文里面的,另存为哪种类型是由new variant()里面的参数决定的。
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(WORD_HTML) }, new int[1]);
new Variant(),这里面的根据传入的参数不同,可以另存为不同的类型,但是在网上搜索了一个并没有找到有关这个参数类型的一个说明,自己尝试了一下,结果如下:
0 | Doc |
1 | Dot |
2-5 | Txt |
6 | Rtf |
7 | Txt |
8、10 | htm |
11 | Xml |
12、16 | Docx |
13 | Docm |
14 | Dotx |
15 | Dotm |
17 | |
我使用的是office 2010,不同版本的对应的应该不一样,我是写了这一小段程序来测试另存为的类型的。
1. public class JacobTest {
2. public static void wordToPDF(String docfile, String toFile,int type) {
3. ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
4. try {
5. app.setProperty("Visible", new Variant(false));
6. Dispatch docs = app.getProperty("Documents").toDispatch();
7. Dispatch doc = Dispatch.invoke(
8. docs,
9. "Open",
10. Dispatch.Method,
11. new Object[] { docfile, new Variant(false),
12. new Variant(true) }, new int[1]).toDispatch();
13. //new Variant(type),这里面的type的决定另存为什么类型的文件
14. Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
15. toFile, new Variant(type) }, new int[1]);
16. Variant f = new Variant(false);
17. Dispatch.call(doc, "Close", f);
18. } catch (Exception e) {
19. e.printStackTrace();
20. } finally {
21. app.invoke("Quit", new Variant[] {});
22. }
23. }
24.
25. public static void main(String[] args) {
26. //源文件全路径
27. String docfile ="D:\\服务实施描述报告(企业门户).docx";
28. for (int i = 0; i < 18; i++) {
29. //些路径test为实际存在的目录,s后面为要另存为的文件名
30. String toFile="d:\\test\\s"+i;
31. wordToPDF(docfile, toFile,i);
32. }
33. }
34.}
基本思想是,通过office 2007自带的插件,保存为PDF,然后用ActiveXComponent实现,核心代码如下:
1>.转换类ExcelToPdf.java
packagecom.olive.util;
import java.io.*;
import java.util.Calendar;
import java.util.Date;
importcom.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
publicclass ExcelToPdf {
private String path;
public static boolean runFlag=false;
public ExcelToPdf(String path){
this.path=path;
}
public void saveExcelAsPdf(String filePath,String outFile){
ComThread.InitSTA();
ActiveXComponent actcom=newActiveXComponent("Excel.Application");
try{
System.out.println((newDate()).toString()+" start convert from : "+filePath+" to"+outFile);
actcom.setProperty("Visible", newVariant(false));
Dispatchexcels=actcom.getProperty("Workbooks").toDispatch();
Dispatch excel =Dispatch.invoke(excels,"Open",Dispatch.Method,
new Object[]{filePath,new Variant(false),new Variant(false)},
new int[9] ).toDispatch();
Dispatch.invoke(excel,"SaveAs",Dispatch.Method,newObject[]{outFile,new Variant(57), new Variant(false),
new Variant(57), new Variant(57),newVariant(false), new Variant(true),new Variant(57), new Variant(false),
new Variant(true), new Variant(false) },newint[1]);
Dispatch.call(excel, "Close",new Variant(false));
if(actcom!=null){
actcom.invoke("Quit",new Variant[]{});
actcom=null;
}
ComThread.Release();
File temp=newFile(filePath);
temp.renameTo(newFile(filePath+"."+getDateStr()));
temp=newFile(filePath);
temp.deleteOnExit();
temp=null;
System.out.println((new Date()).toString()+" convert ok :"+filePath+" to "+outFile);
}catch(Exception es){
es.printStackTrace();
}
}
public void listAllFile(){
runFlag=true;
String fileName="",appdex="";
File temp=null;
try{
File [] list=new File(path).listFiles(newFileFilter(){
public boolean accept(File pathname) {
boolean x = false;
if (pathname.getName().toLowerCase().endsWith(".xls")) {
x = true;
}
return x;
}
});
System.out.println((newDate()).toString()+" Total Convert File : "+list.length);
for(int i=0;i<list.length;i++){
fileName=list[i].getName().substring(0,list[i].getName().indexOf("."));
appdex=list[i].getName().substring(list[i].getName().indexOf("."));
temp=new File(path+fileName+".pdf");
if(temp.exists()){
temp.renameTo(newFile(path+fileName+"-"+getDateStr()+".pdf"));
}
saveExcelAsPdf(path+fileName+appdex,path+fileName+".pdf");
}
}catch(Exception ex){
ex.printStackTrace();
}
runFlag=false;
}
public String getDateStr(){
Calendar cl=Calendar.getInstance();
cl.setTime(new Date());
Stringstr=cl.get(Calendar.YEAR)+""+(cl.get(Calendar.MONTH)+1)+""
+cl.get(Calendar.DATE)+""+cl.get(Calendar.HOUR)+""+cl.get(Calendar.MINUTE)+""
+cl.get(Calendar.SECOND);
return str;
}
}
2>.调用类RunTask.java
packagecom.olive.util;
importjava.io.File;
publicclass RunTask {
public static void main(String[] args) throws Exception {
if(args.length==2){
String path=args[0].trim();
Stringfrequence=args[1].trim();
System.out.println("Convert Path : "+path+", Run Frequency :"+frequence);
try{
intseq=Integer.parseInt(frequence);
Filefile=new File(path);
if(file.exists()){
ExcelToPdf et=new ExcelToPdf(path);
while(true){
if(!et.runFlag){
et.listAllFile();
}
Thread.sleep(seq);
}
}else{
System.out.println("Path Not Exist,Pls Comfirm: "+path);
}
}catch(Exception ex){
System.out.println("Pls Check Your Format,Format Must Be: javacom/olive/util/RunTask Path(Exist Path) Frequency(Run Frequency,int)");
ex.printStackTrace();
}
}else{
System.out.println("Parameter Error,Format MustBe: java com/olive/util/RunTask Path(Exist Path) Frequency(RunFrequency,int)");
}
}
}
3>.window调用.bat
remParameter Error,Format Must: java com/olive/util/RunTask Path(Path,Must ExistPath) Frequency(Run Frequency,Integer Number)
rem if you get a error,please set the classpath in the environment variant
rem classpath=E:\stod\jacob\jacob.jar;
java com/olive/util/RunTask Y:/upload/ 20000
4>.注意事项必须要有jacob.jar包,并设置classpath=E:\stod\jacob\jacob.jar,必须要有jacob-1.15-M4-x86.dll文件放在system32目录下面,这些包自己google吧.
5>.以上方法比较被动只能在windows平台,有没更好办法,高手斧正.
packageas.pdf;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class WordAsPDF {
public static void wordToPDF(String docfile,String toFile,int type) {
ActiveXComponent app = new ActiveXComponent("Word.Application"); // 启动word
//ActiveXComponent app = new ActiveXComponent("Excel.Application");// 启动Excel
//ActiveXComponent app = newActiveXComponent("PowerPoint.Application"); // 启动PowerPoint
try{
app.setProperty("Visible", new Variant(false)); //转ppt的时候把false改为了true
Dispatch docs = app.getProperty("Documents").toDispatch(); //word
//Dispatch docs = app.getProperty("Workbooks").toDispatch(); //excel
//Dispatch docs = app.getProperty("Presentations").toDispatch(); //ppt
Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,newObject[] {
docfile, new Variant(false),new Variant(true) }, newint[1]).toDispatch();
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
toFile, new Variant(type) }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f); //转ppt的时候把这两行代码去掉
}catch (Exception e) {
e.printStackTrace();
}finally {
app.invoke("Quit", new Variant[] {});
}
}
public static void main(String[] args) {
//源文件全路径
String docfile="D:\\Downloads\\b.docx";
//String docfile="D:\\Downloads\\a.xls";
//String docfile="D:\\Downloads\\a.ppt";
//些路径test为实际存在的目录,s后面为要另存为的文件名
String toFile="C:\\Documents andSettings\\Administrator\\桌面\\end\\"+17;
//wordToPDF(docfile, toFile,32);//ppt
wordToPDF(docfile, toFile,17);//word
//wordToPDF(docfile, toFile,57);//excel
}
}
需要jacob.jar, jacob.bll放到jdk下
异常:Exception in thread "main"com.jacob.com.ComFailException: Can't map name to dispid: Chart
解决:安装office 补丁------(2007 Microsoft Office 套件 Service Pack 2 (SP2))
最近项目中要实现读写word文件,于是偶就开始在网上和群里查询和询问,终于找到了个叫做Jacob的组件可以搞定这个问题。
第一步,下载Jacob;地址为:http://sourceforge.net/projects/jacob-project/files/jacob-project/
目前最新的版本为jacob-1.15-M4
第二步,部署Jacob;
a。在Eclipse或Myeclipse中建立一个项目(web或普通的java项目都可):JacobDemo;
b。将下载好的jacob-1.15-M4.zip解压,将jacob.jar导入新建立的项目中;
c。将jacob-1.15-M4-x86.dll或jacob-1.15-M4-x64.dll拷贝到C:\WINDOWS\system32,由于我的电脑比较老所以我拷贝的是jacob-1.15-M4-x86.dll。
第三步,在新建立的项目中建立测试类:WordOperate.java,该文件是我在网上拷贝的,特此声明。
1. import com.jacob.activeX.ActiveXComponent;
2. import com.jacob.com.Dispatch;
3. import com.jacob.com.Variant;
4.
5. public class WordOperate {
6. public static void main(String args[]) {
7. ActiveXComponent wordApp = new ActiveXComponent("Word.Application"); // 启动word
8. // Set the visible property as required.
9. Dispatch.put(wordApp, "Visible", new Variant(true));// //设置word可见
10. Dispatch docs = wordApp.getProperty("Documents").toDispatch();
11. // String inFile = "d:\\test.doc";
12. // Dispatch doc = Dispatch.invoke(docs, "Open", Dispatch.Method,
13. // new Object[] { inFile, new Variant(false), new Variant(false)},//参数3,false:可写,true:只读
14. // new int[1]).toDispatch();//打开文档
15. Dispatch document = Dispatch.call(docs, "Add").toDispatch();// create new document
16.
17. //String userName = wordApp.getPropertyAsString("Username");// 显示用户信息
18. /*String userName = wordApp.getProperty("Username");// 显示用户信息
19. System.out.println("用户名:" + userName);*/
20. // 文档对齐,字体设置
21. Dispatch selection = Dispatch.get(wordApp, "Selection").toDispatch();
22. Dispatch align = Dispatch.get(selection, "ParagraphFormat")
23. .toDispatch(); // 行列格式化需要的对象
24. Dispatch font = Dispatch.get(selection, "Font").toDispatch(); // 字型格式化需要的对象
25. // 标题处理
26. Dispatch.put(align, "Alignment", "1"); // 1:置中 2:靠右 3:靠左
27. Dispatch.put(font, "Bold", "1"); // 字型租体
28. Dispatch.put(font, "Color", "1,0,0,0"); // 字型颜色红色
29. Dispatch.call(selection, "TypeText", "Word文档处理"); // 写入标题内容
30. Dispatch.call(selection, "TypeParagraph"); // 空一行段落
31. Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左
32. Dispatch.put(selection, "Text", " ");
33. Dispatch.call(selection, "MoveDown"); // 光标标往下一行
34. //表格处理
35. Dispatch tables = Dispatch.get(document, "Tables").toDispatch();
36. Dispatch range = Dispatch.get(selection, "Range").toDispatch();
37. Dispatch table1 = Dispatch.call(tables, "Add", range, new Variant(3),
38. new Variant(2), new Variant(1)).toDispatch(); // 设置行数,列数,表格外框宽度
39. // 所有表格
40. Variant tableAmount = Dispatch.get(tables, "count");
41. System.out.println(tableAmount);
42. // 要填充的表格
43. Dispatch t1 = Dispatch.call(tables, "Item", new Variant(1))
44. .toDispatch();
45. Dispatch t1_row = Dispatch.get(t1, "rows").toDispatch();// 所有行
46. int t1_rowNum = Dispatch.get(t1_row, "count").getInt();
47. Dispatch.call(Dispatch.get(t1, "columns").toDispatch(), "AutoFit");// 自动调整
48. int t1_colNum = Dispatch.get(Dispatch.get(t1, "columns").toDispatch(),
49. "count").getInt();
50. System.out.println(t1_rowNum + " " + t1_colNum);
51. for (int i = 1; i <= t1_rowNum; i++) {
52. for (int j = 1; j <= t1_colNum; j++) {
53. Dispatch cell = Dispatch.call(t1, "Cell", new Variant(i),
54. new Variant(j)).toDispatch();// 行,列
55. Dispatch.call(cell, "Select");
56. Dispatch.put(selection, "Text", "cell" + i + j); // 写入word的内容
57. Dispatch.put(font, "Bold", "0"); // 字型租体(1:租体 0:取消租体)
58. Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色
59. Dispatch.put(font, "Italic", "1"); // 斜体 1:斜体 0:取消斜体
60. Dispatch.put(font, "Underline", "1"); // 下划线
61. Dispatch Range = Dispatch.get(cell, "Range").toDispatch();
62. String cellContent = Dispatch.get(Range, "Text").toString();
63. System.out.println((cellContent.substring(0, cellContent
64. .length() - 1)).trim());
65. }
66. Dispatch.call(selection, "MoveDown"); // 光标往下一行(才不会输入盖过上一输入位置)
67. }
68. //合并单元格
69. Dispatch.put(selection, "Text", " ");
70. Dispatch.call(selection, "MoveDown"); // 光标标往下一行
71. Dispatch range2 = Dispatch.get(selection, "Range").toDispatch();
72. Dispatch table2 = Dispatch.call(tables, "Add", range2, new Variant(8),
73. new Variant(4), new Variant(1)).toDispatch(); // 设置行数,列数,表格外框宽度
74. Dispatch t2 = Dispatch.call(tables, "Item", new Variant(2))
75. .toDispatch();
76. Dispatch beginCell = Dispatch.call(t2, "Cell", new Variant(1),
77. new Variant(1)).toDispatch();
78. Dispatch endCell = Dispatch.call(t2, "Cell", new Variant(4),
79. new Variant(4)).toDispatch();
80. Dispatch.call(beginCell, "Merge", endCell);
81.
82. for (int row = 1; row <= Dispatch.get(
83. Dispatch.get(t2, "rows").toDispatch(), "count").getInt(); row++) {
84. for (int col = 1; col <= Dispatch.get(
85. Dispatch.get(t2, "columns").toDispatch(), "count").getInt(); col++) {
86.
87. if (row == 1) {
88. Dispatch cell = Dispatch.call(t2, "Cell", new Variant(1),
89. new Variant(1)).toDispatch();// 行,列
90. Dispatch.call(cell, "Select");
91. Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色
92. Dispatch.put(selection, "Text", "merge Cell!");
93. } else {
94. Dispatch cell = Dispatch.call(t2, "Cell", new Variant(row),
95. new Variant(col)).toDispatch();// 行,列
96. Dispatch.call(cell, "Select");
97. Dispatch.put(font, "Color", "1,1,1,0"); // 字型颜色
98. Dispatch.put(selection, "Text", "cell" + row + col);
99. }
100. }
101. Dispatch.call(selection, "MoveDown");
102. }
103. //Dispatch.call(selection, "MoveRight", new Variant(1), new Variant(1));// 取消选择
104. // Object content = Dispatch.get(doc,"Content").toDispatch();
105. // Word文档内容查找及替换
106. Dispatch.call(selection, "TypeParagraph"); // 空一行段落
107. Dispatch.put(align, "Alignment", "3"); // 1:置中 2:靠右 3:靠左
108. Dispatch.put(font, "Color", 0);
109. Dispatch.put(selection, "Text", "欢迎,Hello,world!");
110. Dispatch.call(selection, "HomeKey", new Variant(6));// 移到开头
111. Dispatch find = Dispatch.call(selection, "Find").toDispatch();// 获得Find组件
112. Dispatch.put(find, "Text", "hello"); // 查找字符串"hello"
113. Dispatch.put(find, "Forward", "True");// 向前查找
114. // Dispatch.put(find, "Format", "True");// 设置格式
115. Dispatch.put(find, "MatchCase", "false");// 大小写匹配
116. Dispatch.put(find, "MatchWholeWord", "True"); // 全字匹配
117. Dispatch.call(find, "Execute"); // 执行查询
118. Dispatch.put(selection, "Text", "你好");// 替换为"你好"
119. //使用方法传入的参数parameter调用word文档中的MyWordMacro宏//
120. //Dispatch.call(document,macroName,parameter);
121. //Dispatch.invoke(document,macroName,Dispatch.Method,parameter,new int[1]);
122. //页眉,页脚处理
123. Dispatch ActiveWindow = wordApp.getProperty("ActiveWindow")
124. .toDispatch();
125. Dispatch ActivePane = Dispatch.get(ActiveWindow, "ActivePane")
126. .toDispatch();
127. Dispatch View = Dispatch.get(ActivePane, "View").toDispatch();
128. Dispatch.put(View, "SeekView", "9"); //9是设置页眉
129. Dispatch.put(align, "Alignment", "1"); // 置中
130. Dispatch.put(selection, "Text", "这里是页眉"); // 初始化时间
131. Dispatch.put(View, "SeekView", "10"); // 10是设置页脚
132. Dispatch.put(align, "Alignment", "2"); // 靠右
133. Dispatch.put(selection, "Text", "这里是页脚"); // 初始化从1开始
134. //书签处理(打开文档时处理)
135. //Dispatch activeDocument = wordApp.getProperty("ActiveDocument").toDispatch();
136. Dispatch bookMarks = Dispatch.call(document, "Bookmarks").toDispatch();
137. boolean isExist = Dispatch.call(bookMarks, "Exists", "bookMark1")
138. .getBoolean();
139. if (isExist == true) {
140. Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")
141. .toDispatch();
142. Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
143. Dispatch.put(range1, "Text", new Variant("当前是书签1的文本信息!"));
144. String bookMark1Value = Dispatch.get(range1, "Text").toString();
145. System.out.println(bookMark1Value);
146. } else {
147. System.out.println("当前书签不存在,重新建立!");
148. Dispatch.call(bookMarks, "Add", "bookMark1", selection);
149. Dispatch rangeItem1 = Dispatch.call(bookMarks, "Item", "bookMark1")
150. .toDispatch();
151. Dispatch range1 = Dispatch.call(rangeItem1, "Range").toDispatch();
152. Dispatch.put(range1, "Text", new Variant("当前是书签1的文本信息!"));
153. String bookMark1Value = Dispatch.get(range1, "Text").toString();
154. System.out.println(bookMark1Value);
155.
156. }
157. //保存操作
158. Dispatch.call(document, "SaveAs", "D:/wordOperate.doc");
159. //Dispatch.invoke((Dispatch) doc, "SaveAs", Dispatch.Method, new Object[]{htmlPath, new Variant(8)}, new int[1]); //生成html文件
160. // 0 = wdDoNotSaveChanges
161. // -1 = wdSaveChanges
162. // -2 = wdPromptToSaveChanges
163. //Dispatch.call(document, "Close", new Variant(0));
164. // // worddoc.olefunction("protect",2,true,"");
165. // // Dispatch bookMarks = wordApp.call(docs,"Bookmarks").toDispatch();
166. // // System.out.println("bookmarks"+bookMarks.getProgramId());
167. // //Dispatch.call(doc, "Save"); //保存
168. // // Dispatch.call(doc, "Close", new Variant(true));
169. // //wordApp.invoke("Quit",new Variant[]{});
170. // wordApp.safeRelease();//Finalizers call this method
171. }
172. }
运行即可看到效果,需要说明的是你的电脑上要安装好word。
异常处理:
如果在运行过程中遇到[JACOB] ------>no jacob in thejava.library.path异常,请尝试将 jacob.dll放到System.getProperty("java.library.path")取到的目录下。
1) ActiveXComponent ax = new ActiveXComponent("a1");//构建ActiveX组件实例
其中的a1的值和你需要调用的ActiveX控件有关 MS控件名
a1的值
InternetExplorer
InternetExplorer.Application
Excel
Excel.Application
Word
Word.Application
Powerpoint
Powerpoint.Application
vb/java Script
ScriptControl
windows media Player
WMPlayer.OCX
Outlook
Outlook.Application
Visio
Visio.Application
DAO
DAO.PrivateDBEngine.35
MultiFace
MultiFace.Face