В процессе обработки наших документов Word может остаться несколько пустых строк/пустых абзацев, и удаление этих пустых строк вручную может занять много времени. Поэтому в этой статье будет представлено простое решение для пакетного удаления этих пустых строк/пустых абзацев с помощью Free Spire. Документ для Java.
Установка Способ 1: Скачайте Бесплатный шпиль. Документ для Java и распакуйте его. Затем добавьте Spire.Doc.jar файл в ваше Java-приложение в качестве зависимости.
Метод 2: Вы также можете добавить зависимость jar в проект maven, добавив следующие конфигурации в pom.xml .
com.e-iceblue e-iceblue http://repo.e-iceblue.com/nexus/content/groups/public/ e-iceblue spire.doc.free 3.9.0
Ниже приведен образец документа, который содержит много пустых строк:
Фрагмент кода
import com.spire.doc.*;
import com.spire.doc.documents.*;
public class removeBlankLines {
public static void main(String[] args) {
//Load the sample document
Document document = new Document();
document.loadFromFile("sample2.docx");
//Traverse every section in the word document and remove the null and empty paragraphs
for (Object sectionObj : document.getSections()) {
Section section=(Section)sectionObj;
for (int i = 0; i < section.getBody().getChildObjects().getCount(); i++) {
if ((section.getBody().getChildObjects().get(i).getDocumentObjectType().equals(DocumentObjectType.Paragraph) )) {
String s= ((Paragraph)(section.getBody().getChildObjects().get(i))).getText().trim();
if (s.isEmpty()) {
section.getBody().getChildObjects().remove(section.getBody().getChildObjects().get(i));
i--;
}
}
}
}
//Save the document to file
String result = "removeBlankLines.docx";
document.saveToFile(result, FileFormat.Docx_2013);
}
}
Выход
Оригинал: “https://dev.to/jazzzzz/remove-blank-lines-in-word-document-in-java-4djh”