我怎样利用Java编程创建odt(LibreOffice/OpenOffice Writer)文件?提供一个“hello world”的例子即可。我查看了OpenOffice网站,但文档并不清晰易懂。
我怎样利用Java编程创建odt(LibreOffice/OpenOffice Writer)文件?提供一个“hello world”的例子即可。我查看了OpenOffice网站,但文档并不清晰易懂。
请看一下ODFDOM - the OpenDocument API
ODFDOM是一个免费的OpenDocument格式(ODF)库。它的目的是提供一种简单的通用方式来创建、访问和操作ODF文件,而不需要详细了解ODF规范。它旨在为ODF开发者社区提供一种易于使用、轻量级的编程API,可移植到任何面向对象的语言中。
当前的参考实现是用Java编写的。
// Create a text document from a standard template (empty documents within the JAR)
OdfTextDocument odt = OdfTextDocument.newTextDocument();
// Append text to the end of the document.
odt.addText("This is my very first ODF test");
// Save document
odt.save("MyFilename.odt");
后来
截至本文撰写时(2016-02),我们被告知这些类已经过时了……而OdfTextDocument
API文档告诉你:
自发布0.8.8版本以来,已由Simple API中的org.odftoolkit.simple.TextDocument替换。
这意味着您仍然需要在项目中包含相同的活动 .jar 文件simple-odf-0.8.1-incubating-jar-with-dependencies.jar
,但要解压以下 .jar 文件以获取文档:simple-odf-0.8.1-incubating-javadoc.jar
,而不是odfdom-java-0.8.10-incubating-javadoc.jar
。
顺便说一句,文档链接会下载一个内部标有“0.6.1”的.zip文件,其中包含一堆jar文件……但里面大部分看起来更像是0.8.1。我不知道为什么在“弃用”类的文档中说“从0.8.8开始”,因为几乎所有东西都已经被标记为已弃用。
上述等效的简单代码如下:
odt_doc = org.odftoolkit.simple.TextDocument.newTextDocument()
para = odt_doc.getParagraphByIndex( 0, False )
para.appendTextContent( 'stuff and nonsense' )
odt_doc.save( 'mySpankingNewFile.odt' )
我正在使用Jython,但Java的代码应该很明显。
我没有尝试过,但使用 JOpenDocument可能是一个选择。(它似乎是一个纯Java库,用于生成OpenDocument文件。)
DocumentTemplateFactory templateFactory = new DocumentTemplateFactory();
DocumentTemplate template = templateFactory .getTemplate(new File("template.odt"));
Map data = new HashMap();
data.put("title", "Title of my doc");
data.put("picture", new RenderedImageSource(ImageIO.read(new File("/tmp/lena.png"))));
data.put("answer", "42");
//...
template.createDocument(data, new FileOutputStream("output.odt"));
可选地,可以使用JODConverter将文档转换为PDF、Word、RTF等格式。
在GitHub上,ansgarkonermann/jodreports-examples是一个使用JODReports的示例项目(包含非平凡格式化案例)。
% cat examples/hello.rb
include OCELOT
Text::create "hello" do
paragraph "Hello, world!"
end
这里还有一些例子(包括一两个电子表格示例)在这里。
您可以尝试使用JasperReports来生成报告,然后将其导出为ODS格式。这种方法的好处是:
解决方案可能是JODF Java API Independentsoft公司。 例如,如果我们想使用此Java API创建一个开放文档文件,我们可以执行以下操作:
import com.independentsoft.office.odf.Paragraph;
import com.independentsoft.office.odf.TextDocument;
public class Example {
public static void main(String[] args)
{
try
{
TextDocument doc = new TextDocument();
Paragraph p1 = new Paragraph();
p1.add("Hello World");
doc.getBody().add(p1);
doc.save("c:\\test\\output.odt", true);
}
catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
这个 API 也有 .NET 的解决方案。