java读取word的⼏种⽅式
1.使⽤apache poi组件
先到/index.html去下载poi-bin-3.2-FINAL-20081019.zip压缩包,把⾥⾯的三个jar加⼊⼯程中。下⾯写个测试servlet类。⽐如请求为href="/TestPOI/readword.do?doc=F:/test.doc"
public class ReadwordServlet extends HttpServlet {
static final private String CONTENT_TYPE = "text/html; charset=gb2312";
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
response.setHeader("Content-Disposition", "test.doc");
String doc = Parameter("doc");
String text = null;
try {
text = readDoc(doc);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter out = Writer();
result(request, out, text);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request,response);
}
private void result(HttpServletRequest request, PrintWriter out, String text)
throws ServletException, IOException {
out.println("<h3>DOCBEGIN</h3><br/>");
out.println(text);
out.println("<br/><h3>DOCEND</h3>");
out.close();
}
///使⽤POI的WordExtractor类进⾏读取word内容
下载apacheprivate String readDoc(String doc) throws Exception{
FileInputStream in = new FileInputStream(new File(doc));
WordExtractor extrator = new WordExtractor(in);
String text = Text();
return text;
}
}
2. 使⽤POI的拓展包tm-extractors-0.4.jar
/pub/mirrors/maven2/org/textmining/tm-extractors/0.4/去下载并加⼊⼯程中,它⼀个就够了,不⽤POI.
替换掉原先readDoc(String doc)⽅法就可以。
private String readDoc(String doc) throws Exception{
FileInputStream in = new FileInputStream(new File(doc));
WordExtractor extrator = new WordExtractor();
String text = actText(in);
return text;
}
3. 使⽤FileInputStream流的⽅式:
⽤下⾯替换掉CONTENT_TYPE(因为流对word格式不熟悉⽆法⾃⼰处理,所以只能使⽤word格式了) static final private String CONTENT_TYPE = "application/msword; charset=gb2312";
⽤下⾯替换doPost⽅法内容
response.setContentType(CONTENT_TYPE);
response.setHeader("Content-Disposition", "test.doc");
String doc = Parameter("doc");
FileInputStream fin = new FileInputStream(doc);
OutputStream out = OutputStream();
byte[] bs = new byte[2048];
for(int ad(bs); i>-1; ad(bs)){
out.write(bs, 0, i);
}
fin.close();
out.close();
4. 可以使⽤中间件,效果当然很好,但是要花钱。如:科翰软件的微软office⽹路中间件
www.kehansoft/soaoffice/doclist.asp
或者NTKO Office也可以。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。