读书人

java读取word有几种模式

发布时间: 2012-08-27 21:21:56 作者: rapoo

java读取word有几种方式?


1.使用apache poi组件

?? 先到http://poi.apache.org/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 = request.getParameter("doc");                        String text = null;            try {                text = readDoc(doc);            } catch (Exception e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            PrintWriter out = response.getWriter();            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内容   private String readDoc(String doc) throws Exception{      FileInputStream in = new FileInputStream(new File(doc));       WordExtractor extrator = new WordExtractor(in);    String text = extrator.getText();    return text;   }}

?

2. 使用POI的拓展包tm-extractors-0.4.jar

http://mirrors.ibiblio.org/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 = extrator.extractText(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 = request.getParameter("doc");   FileInputStream fin = new FileInputStream(doc);           OutputStream out = response.getOutputStream();           byte[] bs = new byte[2048];           for(int i=fin.read(bs); i>-1; i=fin.read(bs)){               out.write(bs, 0, i);           }           fin.close();           out.close();

?

4. 可以使用中间件,效果当然很好,但是要花钱。如:科翰软件的微软office网路中间件
??? http://www.kehansoft.com/soaoffice/doclist.asp
??? 或者NTKO Office也可以。

读书人网 >编程

热点推荐