[java] Apache POI를 이용한 Word 문서 인터프리터

Apache POI는 Java에서 Microsoft Office 포맷인 Word, Excel, PowerPoint 등과 상호 작용하기 위한 라이브러리입니다. 이번 포스트에서는 Apache POI를 사용하여 Word 문서를 인터프리팅하는 방법에 대해 알아보겠습니다.

1. Apache POI 설치 및 설정

Apache POI를 사용하기 위해서는 먼저 해당 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 아래의 의존성을 추가하면 됩니다.

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

2. Word 문서 읽기

Apache POI를 이용하여 Word 문서를 읽어오기 위해서는 XWPFDocument 클래스를 사용합니다. 다음은 Word 문서를 읽어와서 내용을 콘솔에 출력하는 예제 코드입니다.

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

import java.io.FileInputStream;
import java.io.IOException;

public class WordInterpreter {

    public static void main(String[] args) {
        String filePath = "path_to_word_document.docx";

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                System.out.println(paragraph.getText());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위 코드에서 path_to_word_document.docx를 실제 Word 문서 경로로 변경한 뒤 실행하면 문서의 모든 단락을 콘솔에 출력합니다.

3. Word 문서 분석 및 처리

Apache POI를 사용하면 Word 문서의 각 부분을 분석하고 필요한 작업을 수행할 수 있습니다. 예를 들어, 특정 키워드를 찾아서 굵은 글꼴로 표시하는 코드를 작성해보겠습니다.

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

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class WordInterpreter {

    public static void main(String[] args) {
        String filePath = "path_to_word_document.docx";

        try (FileInputStream fis = new FileInputStream(filePath);
             XWPFDocument document = new XWPFDocument(fis)) {
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                if (text.contains("키워드")) {
                    XWPFRun run = paragraph.createRun();
                    run.setBold(true);
                }
            }

            String outputPath = "path_to_output_document.docx";
            try (FileOutputStream fos = new FileOutputStream(outputPath)) {
                document.write(fos);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위 코드에서는 문서의 모든 단락을 순회하면서 “키워드”를 포함하는 부분을 찾아서 해당 부분을 굵은 글꼴로 변경합니다. 변경된 문서는 path_to_output_document.docx에 저장됩니다.

4. 결론

Apache POI를 사용하면 Java에서 Word 문서를 쉽게 읽고 처리할 수 있습니다. 위에서 설명한 방법을 통해 Apache POI를 활용하여 Word 문서를 인터프리팅할 수 있습니다.

더 자세한 내용은 Apache POI 공식 문서를 참고하시기 바랍니다.