java读取doc

本文介绍了一种使用Spire.Doc库在Java中批量读取Word文档并提取文本的方法,特别关注于处理含有特定关键字“JAVA”的文档,并将结果写入SQL格式的文本文件。
package com.test;

import com.spire.doc.Document;
import com.spire.doc.Section;
import com.spire.doc.documents.Paragraph;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

public class Main
{
    /**
     * 获取文件下所有的文件路径
     *
     * @param path
     * @param listFileName
     */
    public static void getAllFileName(String path, ArrayList<String> listFileName) {
        File file = new File(path);
        File [] files = file.listFiles();
        String [] names = file.list();
        if(names != null) {
            String[] completNames = new String[names.length];
            for (int i = 0; i < names.length; i++) {
                completNames[i] = path + "\\" + names[i];
            }
            listFileName.addAll(Arrays.asList(completNames));
        }

        for(File a:files){
            if(a.isDirectory()){
                getAllFileName(a.getAbsolutePath()+"\\", listFileName);
            }
        }
    }

    /**
     * 获取word文档中的文本内容
     *
     * @param filePath 文件路径
     * @return word文档中的文本内容
     */
    private static String getDocText(String filePath) {
        Document document = new Document();
        document.loadFromFile(filePath);
        //获取文档中的文本保存为String
        String text = document.getText();
        int len = text.length();
        int firstIndex = text.indexOf("JAVA");
        if(firstIndex != -1){
            return text.substring(text.indexOf("JAVA")+5, len);
        }else{
            return text;
        }
    }

    public static void writeIntoFile(String content, String txtFileName ) {
        FileWriter fWriter= null;
        try {
            fWriter = new FileWriter(txtFileName,true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fWriter.write(content);
        }catch(IOException ex){
            ex.printStackTrace();
        }finally{
            try{
                fWriter.flush();
                fWriter.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    public static void main(String args[] ) throws IOException {
        ArrayList<String> listFileNames = new ArrayList<String>();
        getAllFileName("F:\\data\\401-500", listFileNames);
        for(String name:listFileNames){
          if( name.indexOf(".doc")!=-1 || name.indexOf(".docx")!=-1);
          String content = getDocText(name);
          String name_id = name.substring(name.indexOf(".")-3, name.indexOf("."));
          name_id = name_id.replaceFirst("^0*", "");
          String sql = "insert into pest.patient_report(name, report)  values('"+ name_id + "','" + content + "');\n";
          writeIntoFile(sql,"F:\\read_word_sql");
        }
    }
}

### 使用Java获取Word文档(.doc)的总页数 为了实现这一功能,可以利用Apache POI库来处理Microsoft Office文件。然而需要注意的是,POI本身并不直接提供计算.doc文件页数的功能。通常情况下,对于.docx格式可以通过解析XML结构间接估算页面数量;但对于二进制格式的.doc文件,则更加复杂。 一种解决方案是先将.doc转换成其他易于操作的格式如PDF或HTML,再通过第三方工具统计页码。这里介绍基于DocToHtmlConverter的方式,并借助Jsoup解析HTML从而粗略估计页数: ```java import org.apache.poi.hwpf.HWPFDocument; import org.apache.poi.hwpf.converter.PicturesManager; import org.apache.poi.hwpf.converter.WordToHtmlConverter; import javax.xml.parsers.DocumentBuilderFactory; import java.io.*; import java.nio.file.Files; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DocPageCounter { public static int getPageCount(File docFile) throws Exception { HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(docFile)); WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument()); wordToHtmlConverter.setPicturesManager(new PicturesManager() { @Override public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) { return null; // 不保存图片到磁盘 } }); wordToHtmlConverter.processDocument(wordDocument); StringWriter writer = new StringWriter(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "html"); transformer.transform(new DOMSource(wordToHtmlConverter.getDocument()), new StreamResult(writer)); Pattern pattern = Pattern.compile("<div.*?class=\"section\">", Pattern.CASE_INSENSITIVE | Pattern.DOTALL); Matcher matcher = pattern.matcher(writer.toString()); int count = 0; while (matcher.find()) { count++; } return count; } } ``` 此方法并非精确无误,因为HTML中的`<div>`标签不一定代表实际打印出来的一页纸张[^1]。更准确的做法可能是调用微软Office应用程序接口或者使用商业软件APIs来进行真正的渲染并返回确切的页数信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值