- 论坛徽章:
- 0
|
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
import com.jacob.com.*;
import com.jacob.activeX.*;
/**
*
* @author 将word转换成html文件,单个文件转换 word转换后进程会自动释放, 但是一次只能转一个文件,
* 如果同时转多个就会报错,进程不释放,占资源,所以 写了杀掉进程的代码
*
*/
public class WordtoHtml {
/**
* 文档转换函数
*
* @param docfile
* word文档的绝对路径加文件名(包含扩展名)
* @param htmlfile
* 转换后的html文件绝对路径和文件名(包含扩展名)
*/
public static SimpleDateFormat sdf=new SimpleDateFormat("YYYY-MM-DD HH:mm:ss" ;
public static void change(String docfile, String htmlfile, boolean bestrow) {
if (!bestrow) {
File file = new File(htmlfile);
if (file.exists()) {
System.out.println(sdf.format(new Date())+ " 文件已存在,不转换:"
+ htmlfile);
return;
}
}
System.out.println(sdf.format(new Date()) + " 开始转换:" + docfile);
long start =System.currentTimeMillis();
ActiveXComponent app = new ActiveXComponent("Word.Application" ; // 启动word
try {
app.setProperty("Visible", new Variant(false));
Dispatch docs = app.getProperty("Documents" .toDispatch();
Dispatch doc = Dispatch.invoke(
docs,
"Open",
Dispatch.Method,
new Object[] { docfile, new Variant(false),
new Variant(true) }, new int[1]).toDispatch();
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
htmlfile, new Variant( }, new int[1]);
Variant f = new Variant(false);
Dispatch.call(doc, "Close", f);
long end = System.currentTimeMillis()-start;
System.out.println(sdf.format(new Date()) + " 转换时间:"
+ (end - start) + " 毫秒!" ;
} catch (com.jacob.com.ComFailException e) {
e.printStackTrace();
} finally {
app.invoke("Quit", new Variant[] {});
app = null;
Process process;
int pid = 0;
try {
// 获取系统进程
process = Runtime.getRuntime().exec("tasklist" ;
Scanner in = new Scanner(process.getInputStream());
while (in.hasNextLine()) {
String p = in.nextLine();
if (p.contains("WINWORD.EXE" ) {
System.out.println(sdf.format(new Date())
+ " 获取WINWORD.EXE进程,进程释放" ;
StringBuffer buf = new StringBuffer();
for (int i = 0; i < p.length(); i++) {
char ch = p.charAt(i);
if (ch != ' ') {
buf.append(ch);
}
}
try {
pid = Integer.parseInt(buf.toString().split(
"Console" [0]
.substring("WINWORD.EXE".length()));
} catch (NumberFormatException e) {
e.printStackTrace();
}
Runtime.getRuntime().exec("tskill" + " " + pid);
System.out.println(sdf.format(new Date())
+ " 释放WINWORD.EXE进程成功" ;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] strs) {
long a = System.currentTimeMillis();
WordtoHtml.change("d:\\a.doc", "c:\\a.html", false);
long b = System.currentTimeMillis()-a;
System.out.println(b - a);
//jacob-1.15-M3-x86.dll
//jacob.jar
}
} |
|