将word文档按原格式放在jsp页面里

前几天碰到一个需求:用户要在后台导入word文档,然后在前台直接显示出来。因为网上的控件再怎么样还是比不上word方便。

网上关于这类的讨论也不少,但大多容易误导解决问题的方向。结合网上的资料加上调试,解决办法如下:

1、利用jacob包将用户上传的word文件转换成htm格式,必须是“筛选过的网页”,不然显示不了图片;

2、将转换好的htm格式文档路径存入数据库,读的时候就在数据库里读。

 

jacob1.8包下载地址:http://sourceforge.net/projects/jacob-project/

 

可能会抛出no jacob in java.library.path异常,解决办法如下:

1、 把jacob.dll在 C:/Program Files/Java/jdk1.5.0_08/bin、C:/Program Files/Java/jdk1.5.0_08/jre/bin、 C:/WINDOWS/system32    目录下各.放一份
2、把jacob.jar放入 项目的lib包下

 

将word文档转换为htm格式的java代码如下:

import com.jacob.com.*;
import com.jacob.activeX.*;
import java.io.*;

public class WordToHtml {

//将指定目录下面的指定doc文件转化为HTML并存储在savepaths目录下
 public static void change(String filepaths, String savepaths) {
  File f = new File(filepaths);
  String filename = f.getName();
  String filetype = filename.substring((filename.length() - 3), filename.length());// 取得文件类型
  if (filetype.equals("doc")) {// 判断是否为doc文件
   System.out.println("当前正在转换......");
   // 打印当前目录路径
   System.out.println(filepaths);
   ActiveXComponent app = new ActiveXComponent("Word.Application");// 启动word
   String docpath = filepaths;
   String htmlpath = savepaths + filename.substring(0, (filename.length() - 4));
   String inFile = docpath;
   // 要转换的word文件
   String tpFile = htmlpath;
   // HTML文件
   boolean flag = false;
   try {
    app.setProperty("Visible", new Variant(false));// 设置word不可见
    Object docs = app.getProperty("Documents").toDispatch();
    Object doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { inFile, new Variant(false),new Variant(true) },
      new int[1]).toDispatch();// 打开word文件
    /*
     * new Variant(10)筛选过的网页
     * new Variant(9) 单个文件网页
     * new Variant(8) 另存为网页
     * new Variant(7) 另存为txt格式
     * new Variant(6) 另存为rtf格式
     * new Variant(0) 另存为doc格式
     */
    Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {tpFile, new Variant(10) }, new int[1]);// 作为html格式保存到临时文件
    Variant fl = new Variant(false);
    Dispatch.call(doc, "Close", fl);
    flag = true;
   } catch (Exception e) {
    e.printStackTrace();
   } finally {
    app.invoke("Quit", new Variant[] {});
   }
   System.out.println("转化完毕!");
  }
 }

public static void main(String[] args) {
  //转换目录下的所有doc文件
//  String paths = new String("D://test//");
  String savepaths = new String("D://test//");
//  changeAll(paths, savepaths);
// 
  //转换指定doc文件
  String filepaths = "D://test.doc";
  change(filepaths, savepaths);
 }

}

评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值