JACOB操作Office的一些实例

package net.fiyu.edit;

import com.jacob.activeX.*;
import com.jacob.com.*;

public class WordService extends java.awt.Panel {
 private static final long serialVersionUID=-1L;

 public ActiveXComponent MsWordApp = null;
 private Dispatch document = null;
 public WordService() {
     super();
 }
 public void openWord(boolean makeVisible) {
     //Open Word if we/'ve not done it already
     if (MsWordApp == null) {
     MsWordApp = new ActiveXComponent("Word.Application");
     }
     //Set the visible property as required.
     Dispatch.put(MsWordApp, "Visible",
     new Variant(makeVisible));
 }
 
 public void openExcel(boolean makeVisible) {
     //Open Word if we/'ve not done it already
     if (MsWordApp == null) {
     MsWordApp = new ActiveXComponent("Excel.Application");
     }
     //Set the visible property as required.
     Dispatch.put(MsWordApp, "Visible",
     new Variant(makeVisible));
 }
 
 /**
     * 打开已知的word文档
     * @param markVisible 可视化状态
     * @param docPath 文档路径
     */
 public void openWord(boolean markVisible,final String docPath) {
     if (MsWordApp == null) {
      MsWordApp = new ActiveXComponent("Word.Application");
      }
      //Set the visible property as required.
     Dispatch.put(MsWordApp, "Visible", new Variant(markVisible));
           Dispatch docs = MsWordApp.getProperty("Documents").toDispatch();
           document = Dispatch.invoke(docs,"Open", Dispatch.Method, new Object[]{docPath}, new int[1]).toDispatch();
 }
 /**
     * 创建Word文档
     *
     */
 public void createNewDocument() {
     //Find the Documents collection object maintained by Word
     Dispatch documents = Dispatch.get(MsWordApp,"Documents").toDispatch();
     //Call the Add method of the Documents collection to create
     //a new document to edit
     document = Dispatch.call(documents,"Add").toDispatch();
 }
 /**
     * 插入文本
     * @param textToInsert
     */
 public void insertText(String textToInsert) {
     // Get the current selection within Word at the moment. If
     // a new document has just been created then this will be at
     // the top of the new doc
     Dispatch selection = Dispatch.get(MsWordApp,"Selection").toDispatch();
     //Put the specified text at the insertion point
     Dispatch.put(selection,"Text",textToInsert);
 }
 public void saveFileAs(String filename) {
     Dispatch.call(document,"SaveAs",filename);
 }
 public void printFile() {
     //Just print the current document to the default printer
     Dispatch.call(document,"PrintOut");
 }
 /**
     * 查找替换文本
     * @param searchText 需要查找的关键字
     * @param replaceText 要替换成的关键字
     */
 public void searchReplace(final String searchText,final String replaceText) {
     Dispatch selection=MsWordApp.getProperty("Selection").toDispatch();
     Dispatch find = ActiveXComponent.call(selection, "Find").toDispatch();
           //查找什么文本
           Dispatch.put(find, "Text", searchText);
           //替换文本
           Dispatch.call(find,"ClearFormatting");
           Dispatch.put(find, "Text", searchText);
           Dispatch.call(find, "Execute");
           Dispatch.put(selection, "Text", replaceText);
 }
 /**
     * 把指定的值设置到指定的标签中去
     * @param bookMarkKey
     */
 public void setBookMark(final String bookMarkKey,final String bookMarkValue) {
          Dispatch activeDocument=MsWordApp.getProperty("ActiveDocument").toDispatch();
          Dispatch bookMarks = ActiveXComponent.call(activeDocument, "Bookmarks").toDispatch();
          boolean bookMarkExist1=Dispatch.call(bookMarks,"Exists",bookMarkKey).getBoolean();
          if(bookMarkExist1==true){
            Dispatch rangeItem = Dispatch.call(bookMarks, "Item",bookMarkKey).toDispatch();
            Dispatch range = Dispatch.call(rangeItem, "Range").toDispatch();
            //取标签的值
            //String bookMarkValue=Dispatch.get(range,"Text").toString();
            //bookMarkValue="test";
            if(bookMarkValue!=null){
                   Dispatch.put(range, "Text",new Variant(bookMarkValue));
            }       
          }else{
            System.out.println("not exists bookmark!");
          }
 }
 /**
     * 保存Word文档到指定的目录(包括文件名)
     * @param filePath
     */
 public void saveWordFile(final String filePath) {
       //保存文件
          Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[] {filePath, new Variant(0)}                        , new int[1]);
          //作为word格式保存到目标文件
          Variant f = new Variant(false);
          Dispatch.call(document, "Close", f);
 }
 public void closeDocument() {
     // Close the document without saving changes
     // 0 = wdDoNotSaveChanges
     // -1 = wdSaveChanges
     // -2 = wdPromptToSaveChanges
     Dispatch.call(document, "Close", new Variant(0));
     document = null;
 }
 public void closeWord() {
     Dispatch.call(MsWordApp,"Quit");
     MsWordApp = null;
     document = null;
 }

public static void main(String[] args) {
       WordService word=new WordService();
       word.openWord(true);
       word.createNewDocument();
       //word.insertText("Hello word.");
       //word.searchReplace("Hello", "哈喽");
       //word.setBookMark("bookMarkKey","bookMarkValue");
       //word.MsWordApp.setProperty("UserName","xiantongsky");
       //word.saveWordFile("D:/xiantong.doc");
 }
 }

 

###############################################################################################################

package net.fiyu.edit;

import java.io.File;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class Wordtohtml
{
//------------------------------------------------------------------------------
//方法原型: change(String paths)
//功能描述: 将指定目录下面所有的doc文件转化为HTML并存储在相同目录下
//输入参数: String
//输出参数: 无
//返 回 值: 无
//其它说明: 递归
//------------------------------------------------------------------------------
 public static void change(String paths, String savepaths)
 {
  
  File d = new File(paths);
  //取得当前文件夹下所有文件和目录的列表
  File lists[] = d.listFiles();
  String pathss = new String("");

  //对当前目录下面所有文件进行检索
  for(int i = 0; i < lists.length; i ++)
  {
   if(lists[i].isFile())
   {
    String filename = lists[i].getName();
    String filetype = new String("");
    //取得文件类型
    filetype = filename.substring((filename.length() - 3), filename.length());
   
    //判断是否为doc文件
    if(filetype.equals("doc"))
    {
     System.out.println("当前正在转换......");
     //打印当前目录路径
     System.out.println(paths);
     //打印doc文件名
     System.out.println(filename.substring(0, (filename.length() - 4)));
    
     ActiveXComponent app = new ActiveXComponent("Word.Application");//启动word
    
     String docpath = paths + filename;
     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((Dispatch) docs,"Open", Dispatch.Method, new Object[]{inFile,new Variant(false), new Variant(true)}, new int[1]).toDispatch();
        //打开word文件
      Dispatch.invoke((Dispatch) doc,"SaveAs", Dispatch.Method, new Object[]{tpFile,new Variant(8)}, new int[1]);
        //作为html格式保存到临时文件
      Variant f = new Variant(false);
      Dispatch.call((Dispatch) doc, "Close", f);
      flag = true;
     }
     catch (Exception e)
     {
      e.printStackTrace();
     }
     finally
     {
      app.invoke("Quit", new Variant[] {});
     }
     System.out.println("转化完毕!");
    }
   }
   else
   {
    pathss = paths;
    //进入下一级目录
    pathss = pathss + lists[i].getName() + "//";   
    //递归遍历所有目录
    change(pathss, savepaths);
   }
  }
 
 }
//------------------------------------------------------------------------------
//方法原型: main(String[] args)
//功能描述: main文件
//输入参数: 无
//输出参数: 无
//返 回 值: 无
//其它说明: 无
//------------------------------------------------------------------------------ 
 public static void main(String[] args)
 {
 
  String paths = new String("D://word//");
  String savepaths = new String ("D://html//");

  change(paths, savepaths);

 }
}


#################################################################################################################

package net.fiyu.edit;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class ExcelTest
{
  private static ActiveXComponent xl;
  private static Object workbooks = null;
  private static Object workbook = null;
  private static Object sheet = null;
  private static String filename =null;
  private static boolean readonly = false;
  private static Dispatch document = null;
 
  public static void main(String[] args)
  {
     String file = "d://new_department_data.xls";
     OpenExcel(file,true);//false为不显示打开Excel
     SetValue("A1","Value","2");
     System.out.println(GetValue("A3"));
     //CloseExcel(false);
  
   //createNewDocument();
  
  }
 
  //打开Excel文档
  private static void OpenExcel(String file,boolean f)
  {
    try
    {
        filename = file;
        xl = new ActiveXComponent("Excel.Application");
        xl.setProperty("Visible", new Variant(f));
        workbooks = xl.getProperty("Workbooks").toDispatch();
         workbook = Dispatch.invoke((Dispatch) workbooks,
                "Open",
                Dispatch.Method,
                                    new Object[]{filename,
                                    new Variant(false),
                                    new Variant(readonly)},//是否以只读方式打开
                                    new int[1] ).toDispatch();
    }catch(Exception e)
    {e.printStackTrace();}
  }
 
 
  public static void createNewDocument() {
      xl = new ActiveXComponent("Excel.Application");
     //Find the Documents collection object maintained by Word
     Dispatch documents = Dispatch.get(xl,"Documents").toDispatch();
     //Call the Add method of the Documents collection to create
     //a new document to edit
     document = Dispatch.call(documents,"Add").toDispatch();
 }
 
  //关闭Excel文档
  private static void CloseExcel(boolean f)
  {
   try
   {  
     Dispatch.call((Dispatch) workbook,"Save");
         Dispatch.call((Dispatch) workbook, "Close", new Variant(f));
      } catch (Exception e) {
         e.printStackTrace();
     } finally {
     xl.invoke("Quit", new Variant[] {});
      }
  }
 
  //写入值
  private static void SetValue(String position,String type,String value)
  {
     sheet = Dispatch.get((Dispatch) workbook,"ActiveSheet").toDispatch();
     Object cell = Dispatch.invoke((Dispatch) sheet, "Range",
             Dispatch.Get,
                                    new Object[] {position},
                                    new int[1]).toDispatch();
      Dispatch.put((Dispatch) cell, type, value);
  }

  //读取值 
  private static String GetValue(String position)
  {
    Object cell = Dispatch.invoke((Dispatch) sheet,"Range",Dispatch.Get,new Object[] {position},new int[1]).toDispatch();
  String value = Dispatch.get((Dispatch) cell,"Value").toString();
 
  return value;
  }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值