java通过jacob来读取word转换为htm格式

转自:http://blog.csdn.net/chinapi_hzh/article/details/5798689

因为微软没有公开word源代码,所以直接用java流来读取word的后果是读出来的全是乱码。所以必须通过jacob这个中间桥 。当然也可用poi来读取。
     先说用poi读取的方法吧。用poi读取的话,先要下载tm-extractors-0.4.jar百度一下可以找到。代码如下:
         

 1 import java.io.FileInputStream;
 2 
 3 try {
 4             FileInputStream fileinputstream = new FileInputStream(filepath);
 5             WordExtractor extractor = new WordExtractor();
 6             temp = extractor.extractText(fileinputstream);
 7             System.out.println(temp + "==temp");
 8             fileinputstream.close();
 9         } catch (Exception ex) {
10             System.out.println("FileNotFoundException error" + ex.getMessage());
11         }


filepath为word文档路径,返回一个temp字符串。这样读出来的不是乱码了,但是效果并不如意。因为把word格式给丢掉了。
再说用jacob. 先到官方网站上去下载:http://sourceforge.net/project/showfiles.php?group_id=109543&package_id=118368 jacob.zip.    下载之后解压,把jacob.jar放到项目/web-inf/lib下面。把jacob .dll放到c:/windos/system32/以及java/jdk*.*/jre/bin下面。这样就算是配置完成了。说代码:

 1 import com.jacob.activeX.ActiveXComponent;
 2 import com.jacob.com.Dispatch;
 3 import com.jacob.com.Variant;
 4 public boolean ChageFormat (String FolderPath,String FileName){
 5      String FileFormat = "";
 6      System.out.println(FolderPath);
 7      FileFormat = FileName.substring(FileName.length()-4,FileName.length());
 8      System.out.println(FileFormat);
 9      if(FileFormat.equalsIgnoreCase(".doc"))
10      {
11          String DocFile = FolderPath +"//"+ FileName;
12          System.out.println("word文件路径:"+DocFile);
13          //word文件的完整路径
14          String HtmlFile = DocFile.substring(0, (DocFile.length() - 4)) + ".htm";
15          System.out.println("htm文件路径:"+HtmlFile);
16          //html文件的完整路径
17          ActiveXComponent app = new ActiveXComponent("Word.Application");
18          //启动word
19          try
20          {
21            app.setProperty("Visible", new Variant(false));
22            //设置word程序非可视化运行
23            Dispatch docs = app.getProperty("Documents").toDispatch();
24            Dispatch doc = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{DocFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch(); 
25            //打开word文件
26            Dispatch.invoke(doc,"SaveAs",Dispatch.Method, new Object[]{HtmlFile,new Variant(8)}, new int[1]);
27            //作为htm格式保存文件
28            Dispatch.call(doc, "Close",new Variant(false));
29            //关闭文件
30          }
31          catch (Exception e)
32          {
33            e.printStackTrace();
34          }
35          finally
36          {
37            app.invoke("Quit", new Variant[] {});
38            //退出word程序
39          }
40          //转化完毕
41          return true;
42      }
43      return false;
44    }


FolderPath为word存放路径。FileName为word名称。通过这个方法就把word文件转成的htm文件。这时候就可以用流来读取htm文件了,读出来的既不是乱码。并且带有格式。
另外要强调的是jacob这个组件和jdk,以及windows版本都有关系。所以版本一定要匹配。否则会报错。版本的问题就要挨个去试了。没有捷径可走。

原文地址:https://www.cnblogs.com/x_wukong/p/4270938.html