如何从.odt文件中获取文本

时间:2016-07-07 16:22:45

标签: c# odt odf aodl

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

我的"尝试"

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

但我无法弄清楚如何使用doc文档进行迭代。

1 个答案:

答案 0 :(得分:2)

最后,我想通了。这是我创建的用于提取所有文本的方法。也许并不完整,因为我不知道构成.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();
    }
相关问题