How to grab text from .odt file

别来无恙 提交于 2019-12-10 13:10:34

问题


I need to grab all text from odf files (open document format) in C#. I found AODL library, and installed it. I visited AODL's page https://wiki.openoffice.org to find examples on how to do the task I need, but they were all unsuccessful. For a reason that I can't imagine, all examples build new document, and there's no example in how to load a document and grab all the text (something like OpenXML). Do you guys know any reference that can guide me?

My "try"

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

But I can't figure out how to iterate with the doc document.


回答1:


Finally, I figured out. This is the method I created to extract all the text. Maybe is not complete, because I don't know all the parts that form the .odt file. This method grabs headers and footers, textboxes and paragraphs and concatenate it with return carriage separator. You need the AODL package, that can be installed through package manager console: PM> Install-Package AODL. And add

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

at the top of your program.

/// <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();
    }


来源:https://stackoverflow.com/questions/38250654/how-to-grab-text-from-odt-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!