使用apache poi向.docx添加注释时文件内容损坏:springboot

时间:2019-03-28 18:15:08

标签: apache-poi

在Windows和Mac OS上使用MS Office Word打开文件时,出现文件内容损坏的弹出窗口。我已经使用apache-poi库在.docx文件中的段落中的句子中添加了注释,但是我无法打开下载的文件。请帮我解决这个问题。

我尝试通过更改项目中的apache poi版本。还尝试了许多其他方法。

以下是我为在.docx文件中添加注释而编写的代码

public MyXWPFCommentsDocument createCommentsDocument(String path, 

XWPFDocument document) throws Exception {
        OPCPackage oPCPackage = document.getPackage();
        PackagePartName partName = PackagingURIHelper.createPartName(path + "/comments.xml");
        PackagePart part;
        if (oPCPackage.containPart(partName)) {
            part = oPCPackage.getPart(partName);
        } else {
            part = oPCPackage.createPart(partName,
                    "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml");
        }
        MyXWPFCommentsDocument myXWPFCommentsDocument = new MyXWPFCommentsDocument(part);

        String rId = "rId" + (document.getRelationParts().size() + 1);
        document.addRelation(rId, XWPFRelation.COMMENT, myXWPFCommentsDocument);
        return myXWPFCommentsDocument;
}


public File updateFile(File file, File xmlfile, CLMDocument clmDoc, String path) throws Exception {

        FileInputStream fis;

        fis = new FileInputStream(file);

        XWPFDocument document = new XWPFDocument(fis);

        MyXWPFCommentsDocument myXWPFCommentsDocument = createCommentsDocument(path, document);

        CTComments comments = myXWPFCommentsDocument.getComments();

        CTComment ctComment;
...

BigInteger cId = BigInteger.ZERO;
                                ctComment = comments.addNewComment();
                                ctComment.setAuthor("Admin");
                                ctComment.setInitials("AR");
                                ctComment.setDate(new GregorianCalendar(Locale.UK));
                                ctComment.addNewCommentRangeStart().setId(cId);
                                ctComment.addNewCommentRangeEnd().setId(BigInteger.TEN);
                                ctComment.setId(cId);
                                ctComment.addNewP().addNewR().addNewT().setStringValue("comment text for the sentence");
                                paragraph.removeRun(k);

                                paragraph.getCTP().addNewCommentRangeStart().setId(cId);
                                XWPFRun run112 = paragraph.insertNewRun(k);
                                paragraph.getCTP().addNewCommentRangeEnd().setId(BigInteger.TEN);
                                run112.getCTR().addNewCommentReference().setId(cId);
                                run112.setText(clmSentence.getsText());
                                run112.addBreak(BreakClear.LEFT);

document.write(new FileOutputStream(file.getAbsolutePath()));
        document.close();
return file;
}

我希望我应该能够在Windows和Mac上的MS Office Word中打开更新的文件,而不会出现内容损坏错误。生成的文件也应该可以下载。

0 个答案:

没有答案