【问题标题】:How to grab text from .odt file如何从 .odt 文件中获取文本
【发布时间】:2016-11-10 01:52:23
【问题描述】:

我需要在 C# 中从 odf 文件(打开文档格式)中获取所有文本。我找到了 AODL 库,并安装了它。 我访问了 AODL 的页面 https://wiki.openoffice.org 以查找有关如何完成我需要的任务的示例,但都没有成功。由于我无法想象的原因,所有示例都构建了新文档,并且没有关于如何加载文档和获取所有文本的示例(类似于 OpenXML)。你们知道任何可以指导我的参考吗?

我的“尝试”

var doc = new AODL.Document.TextDocuments.TextDocument();
        doc.Load(@"C:\path/to/Sample.odt");

但我不知道如何迭代 doc 文档。

【问题讨论】:

  • 您考虑过使用 Novacode DocX 库吗?我过去曾使用它来创建或操作 Word 文档。这是 codeplex 上的链接:docx.codeplex.com
  • 我需要它来读取 odf (open office) 文件,我认为 DocX 只是读取 .docx 文件
  • 如果您无法访问您的 .odt 文件,您可以先将文件另存为 .docx,然后使用 Word 库读取它。
  • 你知道从 odt 转换为 docx 或 doc 或 rtf 的库吗?
  • 你真的不需要图书馆。只需在 OpenOffice 中将文件另存为 .docx。

标签: c# odt odf aodl


【解决方案1】:

终于,我想通了。这是我创建的用于提取所有文本的方法。也许不完整,因为我不知道构成 .odt 文件的所有部分。此方法抓取页眉和页脚、文本框和段落,并将其与回车分隔符连接起来。您需要可以通过包管理器控制台安装的 AODL 包:PM> Install-Package AODL。并添加

using AODL.Document.TextDocuments;
using AODL.Document.Content;

在程序的顶部。

/// <summary>
    /// Gets all plain text from an .odt file
    /// </summary>
    /// <param name="path">
    /// the physical path of the file
    /// </param>
    /// <returns>a string with all text content</returns>
    public String GetTextFromOdt(String path)
    {
        var sb = new StringBuilder();
        using (var doc = new TextDocument())
        {
            doc.Load(path);

            //The header and footer are in the DocumentStyles part. Grab the XML of this part
            XElement stylesPart = XElement.Parse(doc.DocumentStyles.Styles.OuterXml);
            //Take all headers and footers text, concatenated with return carriage
            string stylesText = string.Join("\r\n", stylesPart.Descendants().Where(x => x.Name.LocalName == "header" || x.Name.LocalName == "footer").Select(y => y.Value));

            //Main content
            var mainPart = doc.Content.Cast<IContent>();
            var mainText = String.Join("\r\n", mainPart.Select(x => x.Node.InnerText));

            //Append both text variables
            sb.Append(stylesText + "\r\n");
            sb.Append(mainText);
        }




        return sb.ToString();
    }

【讨论】:

    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2023-02-25
    • 2012-08-07
    相关资源
    最近更新 更多