如何从数据库中读取 Microsoft Word 二进制数据并将其转换为可读文本

How to read Microsoft Word Binary Data from database and convert it to readable text

我在一个名为 Mirth 的 java 应用程序中工作,我需要在其中读取以 Microsoft word 二进制数据格式保存在数据库 table 中的已保存 word 文档。目前我可以从我的 java 应用程序的列中检索数据,但我需要将其转换为可读文本或 XML 或 HTML 格式。

在线查找有一个 java 库调用 Aspose.words,但我找不到任何可以读取此二进制数据并将其转换为可读数据的方法。有没有人使用过 Aspose.words 来完成这样的任务,或者有没有人有替代解决方案

从数据库加载文档

您可以使用 ByteArrayInputStream 加载 Word 文档,如果它在数据库中 table。请参阅 http://www.aspose.com/docs/display/wordsjava/How+to++Load+and+Save+a+Document+to+Database 一篇解释保存和读取 Word 文档 to/from 数据库的文章。我已经从那里复制了相关代码。

public static Document readFromDatabase(String fileName) throws Exception
{
    // Create the SQL command.
    String commandString = "SELECT * FROM Documents WHERE FileName='" + fileName + "'";

    // Retrieve the results from the database.
    ResultSet resultSet = executeQuery(commandString);

    // Check there was a matching record found from the database and throw an exception if no record was found.
    if(!resultSet.isBeforeFirst())
        throw new IllegalArgumentException(MessageFormat.format("Could not find any record matching the document \"{0}\" in the database.", fileName));

    // Move to the first record.
    resultSet.next();

    // The document is stored in byte form in the FileContent column.
    // Retrieve these bytes of the first matching record to a new buffer.
    byte[] buffer = resultSet.getBytes("FileContent");

    // Wrap the bytes from the buffer into a new ByteArrayInputStream object.
    ByteArrayInputStream newStream = new ByteArrayInputStream(buffer);

    // Read the document from the input stream.
    Document doc = new Document(newStream);

    // Return the retrieved document.
    return doc;

}

阅读文字

加载文件后,您可以使用 DOM 阅读它的段落、table、图像等,请参阅 http://www.aspose.com/docs/display/wordsjava/Programming+with+Documents 上的相关文档。

但是,如果您只想从文档中获取所有文本,您可以通过调用 toString() 方法轻松完成,如下所示

System.out.println(doc.toString(SaveFormat.TEXT));

我在 Aspose 工作,担任开发人员推广员。