咱们在解决Word文档时,常常会遇到Word文档中有大量空白行的状况,不仅影响文档好看,还会升高文档的可读性。本文为大家介绍一种收费高效的办法,疾速删除Word文档中的空白行、空白段落。具体操作步骤如下。
引入JAR文件
1. 通过Maven装置
如果你应用Maven,复制以下代码到我的项目文件夹下的“pom.xml“文件中,即可引入JAR文件。
<repositories> <repository> <id>com.e-iceblue</id> <name>e-iceblue</name> <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url></repository></repositories><dependencies> <dependency> <groupId>e-iceblue</groupId> <artifactId>spire.doc.free</artifactId> <version>5.2.0</version> </dependency></dependencies>
2. 手动增加JAR文件
可在Spire.Doc for Java官网下载免费版,解压后,在“Project Structure“中,找到”Modules“,而后在其中的“Dependencies”中,增加解压出的“lib”文件夹下的Spire.Doc.jar文件。
次要代码步骤解析
- 创立Document的对象。
- 用Document.loadFromFile()办法从磁盘中载入Word文档。
- 判断文档中各段落是否为空白行,并用Section.getBody().getChildObjects().remove()办法删除空白行。
- 用Document.saveToFile()办法保存文档到文件。
代码示例:
import com.spire.doc.Document;import com.spire.doc.FileFormat;import com.spire.doc.Section;import com.spire.doc.documents.Paragraph;public class removeEmptyLine { public static void main(String[] args) { //创立Document的对象。 Document document = new Document(); //从磁盘中载入Word文档。 document.loadFromFile("D:/testp/示例1.docx"); //在文档中查找空白行并删除。 for (Object sectionObj : document.getSections()) { Section section = (Section) sectionObj; for (int i = 0; i < section.getBody().getChildObjects().getCount(); i++){ String s = ((Paragraph)(section.getBody().getChildObjects().get(i))).getText().trim(); if (s.isEmpty()) { section.getBody().getChildObjects().remove(section.getBody().getChildObjects().get(i)); i--; } } } String result = "D:/javaOutput/removeEmptyLines.docx"; //保存文档到文件。 document.saveToFile(result, FileFormat.Docx_2013); }}