我正在使用 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
就业证明
兹证明 John 目前受雇于 xxx 担任经理。
约翰从 00 年 12 月 7 日起就在 xxx 工作。
当前的工资是每月的 SalaryPerMonth SalaryCurrencyCode,每周工作 40 小时的 100%。
这里的问题是您正在检索一个字符串中的所有文本。您应该使用“getBodyElements”解析文档中的所有 body 元素,然后遍历所有元素并为每个元素启动一个段落。这是一个如何做到这一点的例子:
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句