public static void main(String[] args) {
String tempUrl = "F:\\SJSAO\\code\\defaultroot\\xtbginforeport\\downloadFileWork\\2022年12月至2023年11月份信息上报统计.doc"; //这个是你文件的地址,tepFile是要转换的文件(xml形式的word文件)
try {
String transDocxName = tempUrl.replace(".doc", ".docx");//将后缀名字替换也是为了在原有的路径上生成新的文件,到后面一定要删除掉这个文件!不然会积很多文件占用内存
Document doc = new Document(tempUrl);// 原始word路径
File wordFile = new File(transDocxName);// 你要的是这个文件********你拿到这个文件就可以了。
FileOutputStream fileOS = new FileOutputStream(wordFile );
doc.save(fileOS, SaveFormat.DOCX);//这里执行操作
//其实aspose.words 是付费的,会产生前后两个水印,这个时候需要调用这个方法将水印清除
removeAsposeMark(transDocxName);//
fileOS.close();
wordFile.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 使用Aspose.Words会出现前后水印可以通过这个方法去除水印
* @param docFilePath
*/
private static void removeAsposeMark(String docFilePath) {
try (FileInputStream in = new FileInputStream(docFilePath)) {
XWPFDocument doc = new XWPFDocument(OPCPackage.open(in));
List<XWPFParagraph> paragraphs = doc.getParagraphs();
if (paragraphs.size() < 1) {
return;
}
XWPFParagraph firstParagraph = paragraphs.get(0);
XWPFParagraph lastParagraph = paragraphs.get(paragraphs.size() - 1);
if (firstParagraph.getText().contains("Aspose.Words")) {
doc.removeBodyElement(doc.getPosOfParagraph(firstParagraph));
doc.removeBodyElement(doc.getPosOfParagraph(lastParagraph));
}
OutputStream out = new FileOutputStream(docFilePath);
doc.write(out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
xml文件转真正的docx文件
于 2023-10-12 10:18:45 首次发布