有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

ApachePOI用于文本,Java代码中的word doc(.docx)中没有进行追加

我尝试使用以下代码来附加word文档中的内容:

    XWPFDocument doc=new XWPFDocument();
    XWPFParagraph para=doc.createParagraph();
    XWPFRun run=para.createRun();
    File f=new File("Text.docx");
    FileOutputStream fos=new FileOutputStream(f, true);
    run.setText("Append The value please");
    doc.write(fos);

但是,程序完成后,当我试图打开文件时,它会说“很抱歉,我们无法打开该文件。我们发现其内容有问题。”

我正在使用以下罐子: 1.Poi 3.12 2.Poi-ooxml-3.10.1 3.Poi-scratchpad-3.15 4.Ooxml-schemas-1.1 5.Xmlbeans-2.3.0 6.Dom4j-1.1

这是什么原因&;有什么办法可以避免这种情况


共 (1) 个答案

  1. # 1 楼答案

    这是因为,您没有使用Apache POI打开文件

    使用XWPFDocument打开word文档以附加数据。Pfb代码

     XWPFDocument doc = new XWPFDocument(OPCPackage.open(fileLocationPath + "Document.doc"));
    
    
        List<XWPFParagraph>  paragraphs = doc.getParagraphs();
    
    
        XWPFParagraph paragraph =  paragraphs.get(paragraphs.size() - 1);
    
        XWPFRun runText = paragraph.createRun();
    
    //if you want to add text
        runText.setText("appending here");
    
    //if you want to add image
        runText.addPicture(java.io.InputStream pictureData, int pictureType, java.lang.String filename, int width, int height)
    
    
    
        try (FileOutputStream out = new FileOutputStream(fileLocationPath + "Document.doc")) {
                doc.write(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
    

    如果要添加图像,请使用XWPFRun的addPicture方法-请参阅此处-Apache POI XWPFRun Add Picture