[java] Apache POI를 이용한 Word 문서 지원

Apache POI는 Java 언어로 만들어진 오픈 소스 라이브러리로, Microsoft Office 포맷인 Word, Excel, PowerPoint 등과 같은 문서를 생성, 수정, 읽기 등의 작업을 지원합니다. 이번 포스트에서는 Apache POI를 사용하여 Word 문서를 지원하는 방법에 대해 알아보겠습니다.

1. Apache POI 라이브러리 추가

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

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

Gradle을 사용하는 경우, build.gradle 파일에 다음 의존성을 추가합니다.

dependencies {
    implementation 'org.apache.poi:poi:4.1.2'
    implementation 'org.apache.poi:poi-ooxml:4.1.2'
}

2. Word 문서 생성

Apache POI를 사용하여 Word 문서를 생성하는 방법은 간단합니다. 다음은 간단한 예제 코드입니다.

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

public class WordDocumentCreator {
    public static void main(String[] args) {
        // 새로운 Word 문서 생성
        XWPFDocument document = new XWPFDocument();

        // 문서에 내용 추가
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello, World!");

        // 문서 저장
        try {
            FileOutputStream out = new FileOutputStream("example.docx");
            document.write(out);
            out.close();
            document.close();
            System.out.println("Word 문서가 성공적으로 생성되었습니다.");
        } catch (Exception e) {
            System.out.println("Word 문서 생성 중 오류가 발생했습니다.");
            e.printStackTrace();
        }
    }
}

위 예제 코드는 새로운 Word 문서를 생성하고 “Hello, World!”라는 내용을 추가한 후, example.docx 파일로 저장하는 코드입니다.

3. Word 문서 수정 및 읽기

Apache POI를 사용하여 Word 문서를 수정하거나 읽는 것도 가능합니다. 예를 들어, 특정 문자열을 찾아서 다른 문자열로 변경하거나, 표의 데이터를 읽어오는 등의 작업을 수행할 수 있습니다.

import org.apache.poi.xwpf.usermodel.*;
import java.io.FileInputStream;

public class WordDocumentModifier {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("example.docx");
            XWPFDocument document = new XWPFDocument(fis);

            // 문서 내용 수정
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    if (text != null && text.contains("Hello")) {
                        run.setText(text.replace("Hello", "안녕하세요"), 0);
                    }
                }
            }

            // 표 데이터 읽기
            for (XWPFTable table : document.getTables()) {
                for (XWPFTableRow row : table.getRows()) {
                    for (XWPFTableCell cell : row.getTableCells()) {
                        String text = cell.getText();
                        System.out.println(text);
                    }
                }
            }

            // 수정된 문서 저장
            FileOutputStream out = new FileOutputStream("modified_example.docx");
            document.write(out);
            out.close();
            document.close();
            System.out.println("Word 문서가 성공적으로 수정되었습니다.");
        } catch (Exception e) {
            System.out.println("Word 문서 수정 중 오류가 발생했습니다.");
            e.printStackTrace();
        }
    }
}

위 예제 코드는 기존에 생성한 example.docx 파일을 읽어와서 “Hello”라는 단어를 “안녕하세요”로 변경하고, 표의 데이터를 출력한 후, 수정된 문서를 modified_example.docx 파일로 저장하는 코드입니다.

참고 자료

Apache POI는 강력하고 유연한 라이브러리로, 많은 기능과 사용 예제를 제공하고 있습니다. 문서 생성, 수정, 읽기 외에도 스타일링, 이미지 삽입, 표 데이터 조작 등 다양한 작업을 할 수 있으니 필요에 따라 자세한 문서를 참고해보시기 바랍니다.