本文介绍使用Spire.Doc for Java批量删除Word文档中的空白段落。
测试文档如下,包含多行空白无内容的段落:
import com.spire.doc.*;
import com.spire.doc.documents.DocumentObjectType;
import com.spire.doc.documents.Paragraph;
public class DeleteBlankParas {
public static void main(String[] args) {
//加载Word测试文档
Document doc = new Document();
doc.loadFromFile("sample.docx");
//遍历Section
for(int i = 0; i < doc.getSections().getCount();i++)
{
//获取section
Section section = doc.getSections().get(i);
//遍历section中的对象
for (int j = 0;j < section.getBody().getChildObjects().getCount();j++)
{
//获取对象类型
Object object = section.getBody().getChildObjects().get(j).getDocumentObjectType();
//遍历段落
for(int z = 0 ; z < section.getParagraphs().getCount();z++)
{
//获取段落
Paragraph paragraph = section.getParagraphs().get(z);
//判断对象类型是否为段落
if(object.equals(DocumentObjectType.Paragraph))
{
//判断段落内容是否为空
if(paragraph.getChildObjects().getLastItem() == null)
{
//删除空白段落
section.getBody().getParagraphs().remove(paragraph);
z--;
}
}
}
}
}
//保存文档
doc.saveToFile("DeleteBlankParas.docx",FileFormat.Docx_2013);
doc.dispose();
}
}
空白段落删除效果: