java使用jacob将word转换为html,如何设置转换后html的编码格式。我想要utf-8的,不要gb2312。

html-css08

java使用jacob将word转换为html,如何设置转换后html的编码格式。我想要utf-8的,不要gb2312。,第1张

强制转码~~

line你要转的内容

line=new String(line.getBytes("gb2312"),"utf-8")代码是我凭记忆写的,应该没问题

或者你在写之前。先写一个HTML页面编码的代码 。把页面的格式设置成utf-8

思路是用一些Java能操作word文件的库,例如Apache的POI库,还有jacob库等,

读出word文件的格式和内容,然后根据格式转换为html(该加粗的加粗,该分段的分段),

这个过程中可以把文字内容提取成txt纯文本文件。

1、到官网下载Jacob,

2、将压缩包解压后,Jacob.jar添加到Libraries中(先复制到项目目录中,右键单击jar包选择Build Path—>Add to Build Path);

3、将Jacob.dll放至当前项目所用到的“jre\bin”下面(比如Eclipse正在用的Jre路径是C:\Java\jdk1.7.0_17\jre\bin)。

Ps:按照上面的步骤配置的,基本没有问题,但是有些电脑可能还会报错,比如:java.lang.UnsatisfiedLinkError: no jacob in java.library.path,这是系统没有加载到jacob.dll,网上解决方法是将Jacob.dll放至“WINDOWS\SYSTEM32”下面。

Java代码:

public class JacobUtil { 

// 8 代表word保存成html 

public static final int WORD_HTML = 8 

public static void main(String[] args) { 

String docfile = "C:\\Users\\无名\\Desktop\\xxx.doc" 

String htmlfile = "C:\\Users\\无名\\Desktop\\xxx.html" 

JacobUtil.wordToHtml(docfile, htmlfile) 

/** 

* WORD转HTML 

* @param docfile WORD文件全路径 

* @param htmlfile 转换后HTML存放路径 

*/ 

public static void wordToHtml(String docfile, String htmlfile) 

// 启动word应用程序(Microsoft Office Word 2003) 

ActiveXComponent app = new ActiveXComponent("Word.Application") 

System.out.println("*****正在转换...*****") 

try 

// 设置word应用程序不可见 

app.setProperty("Visible", new Variant(false)) 

// documents表示word程序的所有文档窗口,(word是多文档应用程序) 

Dispatch docs = app.getProperty("Documents").toDispatch() 

// 打开要转换的word文件 

Dispatch doc = Dispatch.invoke( 

docs, 

"Open", 

Dispatch.Method, 

new Object[] { docfile, new Variant(false), 

new Variant(true) }, new int[1]).toDispatch() 

// 作为html格式保存到临时文件 

Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] { 

htmlfile, new Variant(WORD_HTML) }, new int[1]) 

// 关闭word文件 

Dispatch.call(doc, "Close", new Variant(false)) 

}catch (Exception e){ 

e.printStackTrace() 

}finally{ 

//关闭word应用程序 

app.invoke("Quit", new Variant[] {}) 

System.out.println("*****转换完毕********") 

}