[java] Apache POI를 이용한 Word 문서 마이그레이션

Apache POI는 자바에서 Microsoft Office 파일을 다룰 수 있는 라이브러리입니다. 이번 포스트에서는 Apache POI를 사용하여 Word 문서 마이그레이션을 진행하는 방법에 대해 알아보겠습니다.

목차

Apache POI란?

Apache POI는 자바에서 Microsoft Office 파일을 다룰 수 있는 라이브러리입니다. Excel, Word, PowerPoint 등의 파일을 생성, 편집, 읽기, 쓰기할 수 있습니다. 우리는 이번에 Apache POI를 사용하여 Word 문서의 마이그레이션 작업을 진행할 예정입니다.

Word 문서 마이그레이션

Word 문서 마이그레이션 작업은 크게 세 가지 단계로 이루어집니다. 우선 의존성을 추가한 후, 문서를 읽어와서 작업을 수행하며, 마지막으로 변환된 문서를 저장합니다.

의존성 추가

Apache POI를 사용하기 위해 먼저 Maven 또는 Gradle 프로젝트에 Apache POI 의존성을 추가해야 합니다. 아래는 Maven을 사용하는 경우의 예시입니다.

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

문서 읽기

Apache POI를 통해 Word 문서를 읽어오기 위해서는 XWPFDocument 클래스를 사용합니다. 아래는 Word 문서를 읽어와서 특정 단락의 내용을 출력하는 예시입니다.

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

public class WordDocumentReader {
    public static void main(String[] args) {
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream("document.docx"));
            XWPFParagraph paragraph = document.getParagraphArray(0); // 첫 번째 단락 가져오기
            System.out.println(paragraph.getText());
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

문서 쓰기

Apache POI를 사용하여 Word 문서에 새로운 내용을 작성하기 위해서는 XWPFDocument 클래스를 활용합니다. 아래는 새로운 Word 문서를 생성하고 텍스트를 추가하는 예시입니다.

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

public class WordDocumentWriter {
    public static void main(String[] args) {
        XWPFDocument document = new XWPFDocument();
        XWPFParagraph paragraph = document.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setText("Hello, World!");

        try {
            FileOutputStream outputStream = new FileOutputStream("new_document.docx");
            document.write(outputStream);
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

문서 변환

Apache POI를 사용하여 Word 문서를 다른 형식으로 변환하기 위해서는 XWPFDocument를 활용합니다. 아래는 Word 문서를 PDF 형식으로 변환하는 예시입니다.

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

public class WordDocumentConverter {
    public static void main(String[] args) {
        try {
            XWPFDocument document = new XWPFDocument(new FileInputStream("document.docx"));
            PdfOptions options = PdfOptions.create();

            FileOutputStream outputStream = new FileOutputStream("converted_document.pdf");
            PdfConverter.getInstance().convert(document, outputStream, options);
            document.close();
        } catch (IOException | XWPFConverterException e) {
            e.printStackTrace();
        }
    }
}

마무리

이번 포스트에서는 Apache POI를 사용하여 Word 문서 마이그레이션 작업을 진행하는 방법에 대해 알아보았습니다. Apache POI는 강력한 라이브러리로 다양한 문서 작업을 지원하기 때문에 유용하게 활용할 수 있습니다. 추가적인 정보는 공식 Apache POI 사이트에서 확인할 수 있습니다.