百度空间 | 百度首页 
 
查看文章
 
java生成word html 并保存到数据库
2009年11月03日 星期二 下午 03:20
在最近的一个项目中需要将一段字符类型的文本存为word,html并要将word的内容保存在数据库中,于是就有了如下的一个工具类,希望能对碰到这样需求的朋友提供点帮助。
        匆匆忙忙的就copy上来了,没有做一些删减,有一些多余的东西,有兴趣的朋友可以自行略去。我的注释相对比较清楚,可以按照自己的需求进行组合。
      在操作word的地方使用了jacob(jacob_1.9),这个工具网上很容易找到,将jacob.dll放置系统Path中,直接放在system32下也可以,jacob.jar放置在classPath中。


代码如下:WordBridge.java

/**
* WordBridge.java
*/
package com.kela.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.kela.db.PoolingDataSource;

/**
* 说明: 对word的操作<p>
*
* @author  kela.kf@gmail.com
*/
public class WordBridge {

   Log log =LogFactory.getLog("WordBridgt");

   private ActiveXComponentMsWordApp = null;
    privateDispatch document = null;
   
    /**
     * 打开word
     * @param makeVisible, true显示word, false不显示word
     */
    public voidopenWord(boolean makeVisible) {
       if (MsWordApp == null) {
         MsWordApp = new ActiveXComponent("Word.Application");
       }
  
       Dispatch.put(MsWordApp, "Visible", new Variant(makeVisible));
    }

    /**
     * 创建新的文档
     *
     */
   public voidcreateNewDocument() {
       Dispatch documents = Dispatch.get(MsWordApp,"Documents").toDispatch();
       document = Dispatch.call(documents, "Add").toDispatch();
    }

    /**
     * 关闭文档
     */
    public voidcloseDocument() {
      // 0 = wdDoNotSaveChanges
      // -1 = wdSaveChanges
      // -2 = wdPromptToSaveChanges
      Dispatch.call(document, "Close", new Variant(0));
      document = null;
    }

    /**
     * 关闭word
     *
     */
    public voidcloseWord() {
       Dispatch.call(MsWordApp, "Quit");
       MsWordApp = null;
       document = null;
    }

    /**
     * 插入文本
     * @param textToInsert 文本内容
     */
    public voidinsertText(String textToInsert) {
      Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch();
       Dispatch.put(selection, "Text", textToInsert);
    }

    /**
     * 保存文件
     * @param filename
     */
    public voidsaveFileAs(String filename) {
      Dispatch.call(document, "SaveAs", filename);
    }

    /**
     * 将word转换成html
     * @param htmlFilePath
     */
    public voidwordToHtml(String htmlFilePath) {
         Dispatch.invoke(document,"SaveAs",Dispatch.Method, new Object[]{htmlFilePath,new Variant(8)}, newint[1]);
     }

   /**
     * 保存word的同时,保存一个html
     * @param text 需要保存的内容
     * @param wordFilePath word的路径
     * @param htmlFilePath html的路径
     * @throws LTOAException
     */
    public voidwordAsDbOrToHtml(String text, String wordFilePath, StringhtmlFilePath) throws LTOAException {
  
      try {
         openWord(false);
          createNewDocument();
         insertText(text);
         saveFileAs(wordFilePath);
         wordToHtml(htmlFilePath);
     } catch (Exception ex) {
         log.error("错误 - 对word的操作发生错误");
          log.error("原因- " + ex.getMessage());
          thrownew LTOAException(LTOAException.ERR_UNKNOWN,"对word的操作发生错误("
                    + this.getClass().getName() + ".wordAsDbOrToHtml())", ex);
     } finally {
         closeDocument();
          closeWord();
     }
  
}

   /**
    *将word保存至数据库
    * @paramwordFilePath
    * @paramRecordID
    * @throwsLTOAException
    */
    public voidwordAsDatabase(String wordFilePath, String RecordID) throwsLTOAException {

       Connection conn = null;
        PreparedStatementpstmt = null;
        PoolingDataSourcepool = null;
       
       File file = null;
    
       String sql = "";
       try {
           sql = " UPDATE Document_File SET FileBody = ? WHERE RecordID = ?";
            
            pool= new PoolingDataSource();
           conn = pool.getConnection();
        
           file = new File(wordFilePath);
           InputStream is = new FileInputStream(file);
           byte[] blobByte = new byte[is.available()];
            is.read(blobByte);
           is.close();

          pstmt = conn.prepareStatement(sql);
          pstmt.setBinaryStream(1,(new ByteArrayInputStream(blobByte)),blobByte.length);
          pstmt.setString(2, RecordID);
           pstmt.executeUpdate();
     
        } catch (Exception ex) {
            log.error("错误 - 表 Document_File更新数据发生意外错误");
            log.error("原因 - " + ex.getMessage());
            throw new LTOAException(LTOAException.ERR_UNKNOWN,
                   "表Document_File插入数据发生意外错误("
                    + this.getClass().getName() + ".wordAsDatabase())", ex);
          }finally {
             pool.closePrepStmt(pstmt);
             pool.closeConnection(conn);
        }
    }

   /**
    *得到一个唯一的编号
    * @return编号
    */
   public String getRecordID(){
  
     String sRecordID = "";
  
     java.util.Date dt=new java.util.Date();
        long lg=dt.getTime();
        Long ld=new Long(lg);
        sRecordID =ld.toString();
       
        return sRecordID;
    }

   /**
     * 得到保存word和html需要的路径
     * @param systemType 模块类型 givInfo, sw, fw
     * @param fileType 文件类型 doc, html
     * @param recID 文件编号
     * @return 路径
     */
     public String getWordFilePath(String systemType,String fileType, String recID) {
  
       String filePath = "";
  
       File file = newFile(this.getClass().getResource("/").getPath());

       filePath = file.getPath().substring(0, file.getPath().length() -15);
       
       if(systemType.equalsIgnoreCase("govInfo")) {
   
           if(fileType.equalsIgnoreCase("doc"))
               filePath = filePath + "/uploadFiles/govInfo/document/" + recID +".doc";
            else if(fileType.equalsIgnoreCase("htm"))
               filePath = filePath + "/HTML/govInfo/" + recID + ".htm";
        } else if(systemType.equalsIgnoreCase("sw")){
            if(fileType.equalsIgnoreCase("doc"))
              filePath = filePath +"/uploadFiles/sw/document/" + recID + ".doc";
            else if(fileType.equalsIgnoreCase("htm"))
              filePath = filePath + "/HTML/sw/" + recID +".htm";
         } else if(systemType.equalsIgnoreCase("fw")) {
              if(fileType.equalsIgnoreCase("doc"))
                 filePath = filePath + "/uploadFiles/fw/document/" + recID +".doc";
              else if(fileType.equalsIgnoreCase("htm"))
                 filePath = filePath + "/HTML/fw/" + recID + ".htm";
         }
  
        return filePath;
    }
}


类别:技术_java | 添加到搜藏 | 浏览() | 评论 (0)
 
最近读者:
 
网友评论:
发表评论:
姓 名:
网址或邮箱: (选填)
内 容:
验证码: 请点击后输入四位验证码,字母不区分大小写
      

     

©2009 Baidu