`
kevin_wanwei
  • 浏览: 114538 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Jacob操作Word详细教程

阅读更多

           首先,大家先要了解一下jacob ,官方的解释是Java COM Bridge,即java和 com组件间的桥梁,这里说说为什么我们用jacob操纵word。而不直接使用java去做?

这要原因:在Java开源世界没有很好工具来操作Word文档,POI对word操作还是很不完善,所以我们无法使用它很方便操作word文档来满足我们需求。相比之下使用jacob操作word文档非常方便。也比较容易。

         jacob 下载地址:http://danadler.com/jacob/这个网址还可以下载到源码和例子程序

         jacob 使用方法:将jacob1.7里面jacob.jar添加到我们应用程序环境中,并将 jacob.dl(l就是我前面说的com组件)把放到c:/windows/system32下。如果是web环境中,需要将jacod.jar放到Tomcat的lib目录下.(如果用Tomcat服务器)

        值得注意的是,不同的版本的系统使用不同的dll文件
所以如果你编译成功,但运行失败一般是dll文件问题
遇到这种情况,可以到
http://downloads.sourceforge.net/jacob-project/jacob_1.9.zip?modtime=1109437002&big_mirror=0
下载其他的版本的 dll 文件。

 

下面这段程序是我在别人代码基础上进行一些改进(增加了一些新方法,渴望各位同行批评指正)

package com.bperp.word.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class WordWriter {
		
	private WordOperator word;
	
	public WordWriter(String filePath){
		word=new WordOperator();
		word.openDocument(filePath);
	}
	
	public WordWriter(InputStream input,String filePath,String fileName) throws Exception{
		String path=saveAsDocFile(input,filePath,fileName);
		word=new WordOperator();
		word.openDocument(path);
	}
	/**
	 * 将word文档输入流保存为本地得到word文件
	 * @param input
	 * @param filePath
	 * @param fileName
	 * @throws Exception
	 */
	@SuppressWarnings("unused")
	private String saveAsDocFile(InputStream input,String filePath,String fileName)throws Exception{
		if(!StringUtils.isValidateString(filePath)||!StringUtils.isValidateString(fileName)){
			throw new Exception("The filePath or fileName is error");
		}
		if(input==null){
			throw new Exception("InputStream is null");
		}
		File file=new File(filePath);
		
		if(!file.exists()){
			throw new Exception(" The FilePath is null");
		}
		filePath = validateFilePath(filePath);
		fileName = getRandomFileName(fileName);
	    InputStream	in=null;
	    OutputStream out=null;
	    try{
		    in=new BufferedInputStream(input);
			out=new BufferedOutputStream(new FileOutputStream(filePath+fileName));
			byte[] b=new byte[1024];
			for(int p=0; (p=in.read(b))!=-1;){
				out.write(b);
				out.flush();
			}
	    }finally{
	    	if(out!=null){
	    		out.close();
	    	}
	    	if(in!=null){
	    		in.close();
	    	}
	    }
	    return filePath+fileName;
	}
	/**
	 * 验证Word文件路径
	 * @param filePath
	 * @return
	 */
	private String validateFilePath(String filePath) {
		if((filePath.lastIndexOf("\\\\")==-1)&&(filePath.lastIndexOf("/")==-1)){
			filePath=filePath+"/";
		}
		return filePath;
	}
	/**
	 * 生成一个新的文件名(保证文件名不相同)
	 * @param fileName
	 * @return
	 */
	private String getRandomFileName(String fileName) {
		fileName= fileName + "_"+ new SimpleDateFormat("yyyyMMddHHmmssZ").format(new Date())+".doc";
		return fileName;
	}
	/**
	 * replaceText
	 * @param map
	 */
	public void replaceAllText(Map<String,String> map){
		if(map==null){
			return;
		}
		Set<String> keys=map.keySet();
		Iterator<String> it=keys.iterator();
		while(it.hasNext()){
			String key=it.next();
				word.replaceAllText(key, map.get(key));
		}
	}
	/**
	 * add details
	 * @param values
	 */
	public void insertContextInRow(List<Map<String,String>> values,int tableIndex){
		if(tableIndex<=1){
			tableIndex=1;
		}
		if(values==null||values.size()<=0){
			return;
		}
		int[] p=null;
		Map<String,String> m=values.get(0);
		Set<String> keys=m.keySet();
		Iterator<String> it=keys.iterator();
		while(it.hasNext()){
			String str=it.next();
			
			int[] a=word.getTableCellPostion(str, tableIndex);
			if(a!=null&&a[0]!=0){
				p=a;
			}
			
		}
		if(p!=null&&p[0]!=0){
			for(int i=1;i<values.size();i++){
		      word.addTableRow(tableIndex,p[0]);//在表格插入行数
			}
		}
		
		Iterator<String> it2=keys.iterator();
		while(it2.hasNext()){
			int row=p[0];
			int col=0;
			String str=it2.next();
			
			int[]a=word.getTableCellPostion(str, tableIndex);
			if(a!=null){
				col=a[1];
			}
			for(Map<String,String> map:values){
				word.putTxtToCell(tableIndex, row, col, map.get(str));
				row++;
		    }
		}
		
	}
	
	/**
	 * close document
	 */
	public void close(){
		word.closeDocument();
		word.close();
	}
	/**
	 * 依据Word文件完整路径删除文件
	 * @param path
	 * @throws Exception 
	 */
	public void deleteWordFile(String path) throws Exception{
		File f=new File(path);
		if(!f.exists()){
			throw new Exception("The file is not exists");
		}
		f.delete();
	}
	
	/**
	 * 
	 * @param args
	 * @throws Exception
	 */
	public static void main(String args[]) throws Exception{
		InputStream in=new FileInputStream("d:\\aaa.doc");
		String path="d:\\qq";
		String fileName="aaa";
		WordWriter writer=new WordWriter(in,path,fileName);
		Map<String,String> map1=new HashMap<String,String>();
		map1.put("p21", "上海商哲");
		map1.put("p12", "1550");
		writer.replaceAllText(map1);
		List<Map<String,String>> values =new ArrayList<Map<String,String>>();
		for(int i=0;i<10;i++){
		Map<String,String> map=new HashMap<String,String>();
		map.put("$1", "111111111111");
		map.put("$2", "222222222222");
		map.put("$3", "333333333333");
		map.put("$4", "444444444444");
		map.put("$5", "555555555555");
		map.put("$6", "666666666666");
		values.add(map);
		}
		writer.insertContextInRow(values, 1);
		writer.close();
	}
}

 

5
2
分享到:
评论
5 楼 zihua 2012-09-17  
WordOperator 是你自己写的类吗?
4 楼 aiwwwu 2012-08-23  
博主,你这StringUtils也没有,程序里面也没有说明一下你到底做了哪些功能的示范啊,有点点马虎了~
3 楼 venusf 2012-03-16  
import com.bperp.word.util.StringUtils

楼主这个包在哪里导入啊?

在程序里这个地方会报错,楼主能否把这个文件发给我参考一下? 这是我的邮箱 venusf@163.com  万分感激啊^^
2 楼 xushunwang 2011-01-11  
为什么你的代码中出现的 WordOperator 这个类找不到
1 楼 wangyj0898 2010-05-30  
楼主写的东西都是很实用的,学习了~!

相关推荐

Global site tag (gtag.js) - Google Analytics