java读取ODT文件,如何从.odt文件中获取文本

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.

解决方案

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.

///

/// Gets all plain text from an .odt file

///

///

/// the physical path of the file

///

/// a string with all text content

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

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值