使用POI提取Word文件的内容(纯文本、带html格式)

使用poi提取Word文件的内容,区分带html和不带格式的

 依赖jar导入pom.xml

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>

        <dependency>
            <groupId>fr.opensagres.xdocreport</groupId>
            <artifactId>fr.opensagres.poi.xwpf.converter.xhtml</artifactId>
            <version>2.0.1</version>
        </dependency>

提取工具类:


import com.datahub.aimindgraph.exception.WordExtractorException;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.core.FileURIResolver;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/**
 * @Desc word extraction
 * @Author wadu
 * @Date 2020/1/19
 * @Version 1.0
 **/
public class WordUtil {
    /**
     * word2007
     */
    public final static String DOCX = ".docx";
    /**
     * word2003
     */
    public final static String DOC = ".doc";

    public static void main(String[] args) {
        File file = new File("D:\\temp\\test.doc");
        File imageFolderFile = new File("D:\\temp\\images\\");
        wordToHtmlString(file, imageFolderFile);
    }

    public static String wordToHtmlString(String filePath, String imageFolderPath) {
        return wordToHtmlString(new File(filePath), new File(imageFolderPath));
    }

    public static String wordToString(String filePath) {
        return wordToString(new File(filePath));
    }

    /**
     * 从word获取带html格式的文本
     * @param file
     * @param imageFolderFile
     * @return
     */
    public static String wordToHtmlString(File file, File imageFolderFile) {
        if (!file.exists()) {
            throw new WordExtractorException("file does not exists!");
        } else {
            if (!imageFolderFile.exists()) {
                imageFolderFile.mkdirs();
            }
            if (file.getName().toLowerCase().endsWith(DOCX)) {
                return word2007ToHtmlString(file, imageFolderFile);
            } else if(file.getName().toLowerCase().endsWith(DOC)){
                return word2003ToHtmlString(file, imageFolderFile);
            } else {
                throw new WordExtractorException("Only doc or docx files are supported");
            }
        }
    }

    /**
     * 从word获取不带格式的文本
     * @param file
     * @return
     */
    public static String wordToString(File file) {
        if (!file.exists()) {
            throw new WordExtractorException("file does not exists!");
        } else {
            if (file.getName().toLowerCase().endsWith(DOCX)) {
                return word2007ToString(file);
            } else if(file.getName().toLowerCase().endsWith(DOC)){
                return word2003ToString(file);
            } else {
                throw new WordExtractorException("Only doc or docx files are supported");
            }
        }
    }

    /**
     * @param wordFile
     * @return
     */
    private static String word2007ToString(File wordFile) {
        try(InputStream in = new FileInputStream(wordFile)) {
            StringBuilder result = new StringBuilder();
            XWPFDocument document = new XWPFDocument(in);
            XWPFWordExtractor re = new XWPFWordExtractor(document);
            result.append(re.getText());
            re.close();
            return result.toString();
        } catch (Exception e) {
            throw new WordExtractorException(e.getMessage());
        }
    }

    /**
     * @param wordFile
     * @return
     */
    private static String word2003ToString(File wordFile) {
        try(InputStream in = new FileInputStream(wordFile)) {
            WordExtractor wordExtractor = new WordExtractor(in);
            return wordExtractor.getText();
        } catch (Exception e) {
            throw new WordExtractorException(e.getMessage());
        }
    }

    /**
     *
     * @param wordFile
     * @param imageFolderFile
     * @return
     */
    private static String word2007ToHtmlString(File wordFile, File imageFolderFile) {
        try (InputStream in = new FileInputStream(wordFile);
             XWPFDocument document = new XWPFDocument(in);
             ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));
            options.setExtractor(new FileImageExtractor(imageFolderFile));
            options.setIgnoreStylesIfUnused(false);
            options.setFragment(true);
            XHTMLConverter.getInstance().convert(document, baos, options);
            return baos.toString();
        } catch (Exception e) {
            throw new WordExtractorException(e.getMessage());
        }
    }

    /**
     *
     * @param wordFile
     * @param imageFolderFile
     * @return
     */
    private static String word2003ToHtmlString(File wordFile, File imageFolderFile) {
        String absolutePath = imageFolderFile.getAbsolutePath();
        String imagePath = absolutePath.endsWith(File.separator) ? absolutePath : absolutePath + File.separator;
        try (InputStream input = new FileInputStream(wordFile);
             HWPFDocument wordDocument = new HWPFDocument(input);
             ByteArrayOutputStream baos = new ByteArrayOutputStream();
             OutputStream outStream = new BufferedOutputStream(baos)) {
            WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
            //图片存放的位置
            wordToHtmlConverter.setPicturesManager((content, pictureType, suggestedName, widthInches, heightInches) -> {
                String imageFile = imagePath + suggestedName;
                File file = new File(imageFile);
                try {
                    OutputStream os = new FileOutputStream(file);
                    os.write(content);
                    os.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return imageFile;
            });
            //解析word文档
            wordToHtmlConverter.processDocument(wordDocument);
            Document htmlDocument = wordToHtmlConverter.getDocument();
            DOMSource domSource = new DOMSource(htmlDocument);
            StreamResult streamResult = new StreamResult(outStream);
            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer serializer = factory.newTransformer();
            serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
            serializer.setOutputProperty(OutputKeys.INDENT, "yes");
            serializer.setOutputProperty(OutputKeys.METHOD, "html");
            serializer.transform(domSource, streamResult);
            return baos.toString();
        } catch (Exception e) {
            throw new WordExtractorException(e.getMessage());
        }
    }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: POI是Apache基金会的一个Java API,用于处理Microsoft Office格式文件,包括Word文档中的表格数据。下面是使用POI提取Word文档中表格数据的示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFTable; import org.apache.poi.xwpf.usermodel.XWPFTableRow; import org.apache.poi.xwpf.usermodel.XWPFTableCell; public class TableReader { public static void main(String[] args) throws IOException { File file = new File("example.docx"); FileInputStream fis = new FileInputStream(file); XWPFDocument document = new XWPFDocument(fis); for (XWPFTable table : document.getTables()) { for (XWPFTableRow row : table.getRows()) { for (XWPFTableCell cell : row.getTableCells()) { System.out.print(cell.getText() + "\t"); } System.out.println(); } } document.close(); fis.close(); } } ``` 在这个示例代码中,我们首先打开Word文档并读取其中的表格数据。然后,我们使用POI的XWPFTable、XWPFTableRow和XWPFTableCell类来遍历表格中的每个单元格,并使用getText()方法提取单元格中的文本。最后,我们将提取的表格数据打印到控制台上。 请注意,此示例假定Word文档的文件格式为docx。如果你需要读取早期版本的Word文档,例如.doc格式文件,你需要使用不同的POI类来处理不同的文件格式。 ### 回答2: POI是一个用于处理Microsoft Office格式文件(如Word、Excel和PowerPoint)的Java API。利用POI提取Word文档表格中的表格数据,可以按照以下步骤进行: 1.导入POI库:在Java项目中,首先需要导入POI的相关库文件,可以通过Maven或手动添加jar文件的方式引入POI库。 2.加载Word文档:使用POI的XWPFDocument类,加载需要处理的Word文档。 3.获取表格:通过XWPFDocument类的getTables()方法,可以获取Word文档中的所有表格对象,返回一个Table[]数组。 4.遍历表格:对于每个表格对象,可以使用foreach或for循环依次遍历。 5.获取行和列:对于每个表格对象,可以使用getTableRows()方法获取表格的所有行对象,返回一个List<XWPFTableRow>集合。对于每个行对象,可以使用getTableCells()方法获取表格的所有单元格对象,返回一个List<XWPFTableCell>集合。 6.提取数据:对于每个单元格对象,使用getText()方法可以获取单元格中的文本内容,将其保存到一个数据结构中,如Map、List或二维数组。 7.处理数据:根据需要进行数据的后续处理,如打印输出、存储到数据库或进行其他计算等。 8.关闭文档:处理完毕后,使用XWPFDocument对象的close()方法关闭文档。 使用POI提取Word文档表格中的表格数据,可以方便地进行数据解析和处理,适用于各种需要处理Word表格数据的应用场景。 ### 回答3: POI是一个Java库,可以用来操作Microsoft Office文件(如Word、Excel和PowerPoint)。在POI中,可以使用XWPFDocument类来读取和操作Word文档。 要提取Word文档中的表格数据,首先需要加载Word文档,并使用XWPFDocument类创建一个对象来表示该文档。然后,可以使用getTables()方法来获取文档中的所有表格。对于每个表格,可以使用getRows()方法获取表格中的所有行。对于每一行,再使用getTableCells()方法获取行中的所有单元格。 下面是一个简单的代码示例,演示如何使用POI提取Word文档表格中的表格数据: ``` import org.apache.poi.xwpf.usermodel.*; public class ExtractTableDataFromWord { public static void main(String[] args) { try { // 加载Word文档 XWPFDocument document = new XWPFDocument(new FileInputStream("example.docx")); // 获取文档中的所有表格 List<XWPFTable> tables = document.getTables(); // 遍历每个表格 for (XWPFTable table : tables) { // 获取表格中的所有行 List<XWPFTableRow> rows = table.getRows(); // 遍历每一行 for (XWPFTableRow row : rows) { // 获取行中的所有单元格 List<XWPFTableCell> cells = row.getTableCells(); // 遍历每个单元格,并打印单元格的值 for (XWPFTableCell cell : cells) { System.out.println(cell.getText()); } } } // 关闭文档 document.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 以上代码将读取名为"example.docx"的Word文档中的所有表格,并将每个单元格的值打印到控制台上。这个例子已经简化,如果需要更详细的操作,可以参考POI的官方文档或其他资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值