近日,遇到一个需求,需要用到 aspose.words 开处理 word 文档,将调试通过的一些代码和过程记录如下:
一、对 word 文档文字进行替换
int com.aspose.words.Range.replace(String oldValue, String newValue, boolean isMatchCase, boolean isMatchWholeWord) throws Exception
public static void main(String[] args) {
try {
Document document = new Document("D:/picWord/2020/5/20/cecad28c65ed4f0d8e1efa0f22912787_copy.doc");
document.getRange().replace("Evaluation Warning: The document was created with Spire.Doc for JAVA.", "", false, false);
document.save("D:/picWord/2020/5/20/cecad28c65ed4f0d8e1efa0f22912787_copy11.doc");
} catch (Exception e) {
e.printStackTrace();
}
}
效果演示(左为原文档):
二、删除第一行文本
public static void main(String[] args) {
try {
Document document = new Document("D:/picWord/2020/5/20/cecad28c65ed4f0d8e1efa0f22912787_copy.doc");
ParagraphCollection paras = document.getFirstSection().getBody().getParagraphs();
DocumentBuilder builder = new DocumentBuilder(document);
paras.removeAt(0);
Paragraph firstPara = paras.get(0);
builder.moveTo(firstPara);
document.save("D:/picWord/2020/5/20/cecad28c65ed4f0d8e1efa0f22912787_copy11.doc");
} catch (Exception e) {
e.printStackTrace();
}
}
效果演示(左为原文档):
三、在 word 文件的第一段之前插入一段文本内容
public static void main(String[] args) {
try {
Document document = new Document("D:/picWord/2020/5/20/cecad28c65ed4f0d8e1efa0f22912787_copy.doc");
ParagraphCollection paras = document.getFirstSection().getBody().getParagraphs();
Paragraph newPara = new Paragraph(document);
DocumentBuilder builder = new DocumentBuilder(document);
paras.insert(0, newPara);
Paragraph firstPara = paras.get(0);
builder.moveTo(firstPara);
builder.write("这是插入第一行的数据");
document.save("D:/2020/5/20/cecad28c65ed4f0d8e1efa0f22912787_copy11.doc");
} catch (Exception e) {
e.printStackTrace();
}
}
效果演示(左为原文档):