package army;
import org.apache.commons.io.FileUtils;
import org.odftoolkit.odfdom.doc.OdfTextDocument;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.stream.Collectors;
public class LibreOfficeWriter2 {
public static void main(String[] args) throws Exception {
OdfTextDocument odt = OdfTextDocument.loadDocument("MyFilename.odt");
InputStream contentStream = odt.getContentStream();
String text = new BufferedReader(
new InputStreamReader(contentStream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(contentStream, StandardCharsets.UTF_8));
setText(text);
contentStream.close();
odt.close();
bufferedReader.close();
}
public static void setText(String text) {
try {
FileUtils.writeByteArrayToFile(new File("result.odt"), text.replace("result", "***").getBytes());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
最后,我提取了归档文件,处理和编辑了xml,但是我没有把它打包回去。有人知道怎么做吗?在这里输入图像描述


发布于 2022-05-27 14:46:27
ODF允许您使用OpenOffice/LibreOffice文档(带有扩展OpenDocument的.odt文本)及其以压缩XML格式存储的文本内容。
ODFDOM允许编辑而不需要操作XML。
Java允许您使用抽象层OpenOffice文档对象模型(DOM)直接处理特定的XML结构。
对于修改文本,您可能对文本内容的元素感兴趣,例如,标题的<text:h>或段落的<text:p>。这些XML元素在OpenOffic中分别被建模为类TextHElement和TextPElement。
参见ODFDOM - OpenDocument API的快速启动示例
// 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");打开
要么使用newTextDocument()创建一个新的,要么使用loadDocument(File)方法加载现有的。
修改
使用打开文档的文档对象模型(DOM) (例如odt)来添加、删除或修改元素。DOM包含具有不同节点或元素的树结构(每个节点或元素代表特定的XML元素)。
例如,要获得第一段文本并替换它:
// get the root element inside ODF XML
OdfElement root = odt.getContentRoot();
// count the child elements of root
int childrenCount = root.countChildComponents(true);
System.out.println(childrenCount);
// get a paragraph and its text, e.g. the first
OdfElement firstParagraph = OdfElement.findFirstChildNode(TextPElement.class, root);
System.out.println(firstParagraph.getTextContent());
// modify the text
firstParagraph.setTextContent("Hello World!");用于处理DOM元素的方法:
OdfTextDocument.getContentRoot()OdfElement.countChildComponents(hasTextElements)OdfElement.findFirstChildNode(clazz,node)TextParagraphElementBase.setTextContent(text)保存
使用的save方法是OdfTextDocument的一个特殊方法,它直接接受带有文件名的字符串。
而且,从抽象OpenDocument继承的任何文档都有一个save(File)方法。
https://stackoverflow.com/questions/72405729
复制相似问题