【问题标题】:Write a docx file using Apache POI Word JAVA使用 Apache POI Word JAVA 编写 docx 文件
【发布时间】:2018-07-03 06:06:36
【问题描述】:

我正在使用 Apache POI Word 在 java 中创建一个 docx 文件。

现在我正在使用以下代码

XWPFDocument document = new XWPFDocument();
  XWPFParagraph tmpParagraph = document.createParagraph();
  XWPFRun tmpRun = tmpParagraph.createRun();
  tmpRun.setText(newDocxData);

  try {
     document.write(new FileOutputStream(new File("C:\\test.docx")));
  } catch (FileNotFoundException ex) {
     Logger.getLogger(PersonnelFileHandlingStreamAttributesHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
  } catch (IOException ex) {
     Logger.getLogger(PersonnelFileHandlingStreamAttributesHandlerImpl.class.getName()).log(Level.SEVERE, null, ex);
  }

但这会将整个文本放在一个段落中。

但我想将给定的字符串按原样放入文档中。

我尝试将字符串转换为输入流并在创建文档时传递它

XWPFDocument document = new XWPFDocument(inputstream);

但它也给出了一个错误。有什么解决办法吗?

这是我要编写的字符串示例。

10 - SchaumburgIllinois - 美国 xxx 2018-06-28

在职证明

兹证明约翰目前在 xxx 担任经理。

John 自 2000 年 12 月 7 日起在 xxx 工作。

当前工资是 SalaryPerMonth SalaryCurrencyCode 每月,工作 每周 40 小时的 100%。

【问题讨论】:

  • String newDocxData 究竟包含什么?它从何而来?您需要解析该字符串以将其分成不同的段落和文本运行。
  • 该字符串包含从 Word 文档中提取的一些文本。当我在控制台中打印它时,它会以格式打印。所以我只想创建另一个文档而不添加新段落等等。
  • 你能添加字符串的内容吗?
  • 实际上我正在阅读模板文档并替换一些字符串并创建一个新文件。我认为这会简化我的要求
  • @AxelRichter 知道怎么做吗?

标签: java apache-poi file-writing


【解决方案1】:

这里的问题是您正在检索一个字符串中的所有文本。您应该使用“getBodyElements”解析文档中的所有正文元素,然后遍历所有元素并为每个元素启动一个段落。这是一个如何做到这一点的例子:

 public static XWPFDocument MergeDocument(XWPFDocument source, XWPFDocument output){

        for(IBodyElement element : source.getBodyElements()) {
           if(element instanceof XWPFParagraph) {
                XWPFParagraph paragraph = (XWPFParagraph)element;
                if(paragraph.getStyleID()!=null){
                    XWPFStyles styles= output.createStyles();
                    XWPFStyles stylesdoc2= source.getStyles();
                    styles.addStyle(stylesdoc2.getStyle(paragraph.getStyleID()));
                }    
                XWPFParagraph x= output.createParagraph();
                x.setStyle(((XWPFParagraph) element).getStyle());
                XWPFRun runx=x.createRun();
                runx.setText(((XWPFParagraph) element).getText());
            }
        }
return output;
    }

【讨论】: