我正在尝试从使用Apache poi XWPF生成的.docx文档中删除一个段落。我可以使用HWPF轻松地处理.doc word文档,如下所示:
for (String paraCount : plcHoldrPargrafDletdLst) {
Paragraph ph = doc.getRange().getParagraph(Integer.parseInt(paraCount));
System.out.println("Deleted Paragraph Start & End: " + ph.getStartOffset() +" & " + ph.getEndOffset());
System.out.println("Deleted Paragraph Test: " + ph.text());
ph.delete();
}
我试着用同样的方法
doc.removeBodyElement(Integer.parseInt(paraCount));
但不幸的是,没有达到我想要的结果。结果文档,我看不到段落被删除了。关于如何在XWPF中实现类似功能的任何建议。
发布于 2017-06-02 18:30:19
好吧,这个问题有点老了,可能不再需要了,但我只是找到了一个与建议的解决方案不同的解决方案。
我希望下面的代码能帮助有同样问题的人
...
FileInputStream fis = new FileInputStream(fileName);
XWPFDocument doc = new XWPFDocument(fis);
fis.close();
// Find a paragraph with todelete text inside
XWPFParagraph toDelete = doc.getParagraphs().stream()
.filter(p -> StringUtils.equalsIgnoreCase("todelete", p.getParagraphText()))
.findFirst().orElse(null);
if (toDelete != null) {
doc.removeBodyElement(doc.getPosOfParagraph(toDelete));
OutputStream fos = new FileOutputStream(fileName);
doc.write(fos);
fos.close();
}
发布于 2015-03-30 21:43:09
似乎你真的无法从.docx文件中删除段落。
你应该能够做的是删除段落的内容...所谓的Runs
.You可以试试这个:
List<XWPFParagraph> paragraphs = doc.getParagraphs();
for (XWPFParagraph paragraph : paragraphs)
{
for (int i = 0; i < paragraph.getRuns().size(); i++)
{
paragraph.removeRun(i);
}
}
您还可以指定应该删除哪个段落的哪个运行,例如
paragraphs.get(23).getRuns().remove(17);
发布于 2018-06-22 21:58:17
版权所有
// Remove all existing runs
removeRun(para, 0);
public static void removeRun(XWPFParagraph para, int depth)
{
if(depth > 10)
{
return;
}
int numberOfRuns = para.getRuns().size();
// Remove all existing runs
for(int i = 0; i < numberOfRuns; i++)
{
try
{
para.removeRun(numberOfRuns - i - 1);
}
catch(Exception e)
{
//e.printStackTrace();
}
}
if(para.getRuns().size() > 0)
{
removeRun(para, ++depth);
}
}
https://stackoverflow.com/questions/29343921
复制相似问题