您的位置:首页 > 其它

poi操作word

2015-03-14 23:56 253 查看

poi操作word

1、环境支持

1.1 添加poi支持:包下载地址http://www.apache.org/dyn/closer.cgi/poi/release/

1.2 POI对Excel文件的读取操作比较方便,POI还提供对Word的DOC格式文件的读取。但在它的发行版本中没有发布对Word支持的模块,需要另外下载一个POI的扩展的Jar包。下载地址为http://www.ibiblio.org/maven2/org/textmining/tm-extractors/0.4/ 下载extractors-0.4_zip这个文件

2、提取Doc文件内容




public static String readDoc(String doc) throws Exception
{


// 创建输入流读取DOC文件


FileInputStream in = new FileInputStream(new File(doc));


WordExtractor extractor = null;


String text = null;


// 创建WordExtractor


extractor = new WordExtractor();


// 对DOC文件进行提取


text = extractor.extractText(in);


return text;


}




public static void main(String[] args) {




try{


String text = WordReader.readDoc("c:/test.doc");


System.out.println(text);




}catch(Exception e){


e.printStackTrace();


}


}

3、写入Doc文档
import java.io.ByteArrayInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

import org.apache.poi.poifs.filesystem.DirectoryEntry;

import org.apache.poi.poifs.filesystem.DocumentEntry;

import org.apache.poi.poifs.filesystem.POIFSFileSystem;

public class WordWriter {

public static boolean writeDoc(String path, String content) {

boolean w = false;

try {

// byte b[] = content.getBytes("ISO-8859-1");

byte b[] = content.getBytes();

ByteArrayInputStream bais = new ByteArrayInputStream(b);

POIFSFileSystem fs = new POIFSFileSystem();

DirectoryEntry directory = fs.getRoot();

DocumentEntry de = directory.createDocument("WordDocument", bais);

FileOutputStream ostream = new FileOutputStream(path);

fs.writeFilesystem(ostream);

bais.close();

ostream.close();

} catch (IOException e) {

e.printStackTrace();

}

return w;

}

public static void main(String[] args) throws Exception{

String wr=WordReader.readDoc("D:\\test.doc");

boolean b = writeDoc("D:\\result.doc",wr);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: