[java] Apache POI를 이용한 Word 문서 필터링

Apache POI는 자바로 개발된 라이브러리로, Microsoft Office 포맷인 Word, Excel, PowerPoint 등과 같은 문서를 다룰 수 있습니다. 이번 포스트에서는 Apache POI를 사용하여 Word 문서를 필터링하는 방법에 대해 알아보겠습니다.

필요한 라이브러리 설치

먼저 Apache POI를 사용하기 위해서는 해당 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 다음과 같이 의존성을 추가할 수 있습니다:

<dependencies>
    <dependency>
        <groupId>org.apache.poi</groupId>
        <artifactId>poi</artifactId>
        <version>4.1.2</version>
    </dependency>
</dependencies>

코드 예제

다음은 Apache POI를 사용하여 Word 문서를 필터링하는 예제 코드입니다:

import org.apache.poi.xwpf.usermodel.*;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class WordDocumentFilter {

    public static void filterDocument(String inputFilePath, String outputFilePath, String filterText) throws IOException {
        FileInputStream fis = new FileInputStream(inputFilePath);
        XWPFDocument document = new XWPFDocument(fis);

        // 모든 텍스트를 순회하면서 필터링
        Iterator<XWPFParagraph> paragraphIterator = document.getParagraphsIterator();
        while (paragraphIterator.hasNext()) {
            XWPFParagraph paragraph = paragraphIterator.next();
            String text = paragraph.getText();
            if (text.contains(filterText)) {
                // 필터링에 포함된 텍스트가 있는 문단 삭제
                document.removeBodyElement(document.getPosOfParagraph(paragraph));
            }
        }

        fis.close();

        FileOutputStream fos = new FileOutputStream(outputFilePath);
        document.write(fos);
        fos.close();
    }

    public static void main(String[] args) {
        String inputFilePath = "input.docx";
        String outputFilePath = "output.docx";
        String filterText = "필터링할 단어";

        try {
            filterDocument(inputFilePath, outputFilePath, filterText);
            System.out.println("문서 필터링이 완료되었습니다.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

코드 설명

위의 예제 코드는 주어진 입력 파일에서 지정한 필터링 텍스트가 포함된 문단을 제거한 뒤, 결과를 출력 파일로 저장하는 예제입니다. filterDocument 메서드는 입력 파일 경로, 출력 파일 경로, 필터링할 텍스트를 매개변수로 받아 처리합니다.

마무리

이번 포스트에서는 Apache POI를 사용하여 Word 문서를 필터링하는 방법을 알아보았습니다. Apache POI는 다양한 기능을 제공하므로 문서 처리와 관련된 작업을 자바로 수행해야 하는 경우 유용하게 사용할 수 있습니다. 추가적인 기능 및 사용법은 Apache POI 공식 문서를 참고하시기 바랍니다.