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

Apache POI는 Java에서 Microsoft Office 파일을 다루는 라이브러리입니다. 이 라이브러리를 사용하면 Java에서 Word, Excel, PowerPoint 등의 문서를 생성, 수정 및 조작할 수 있습니다.

이번에는 Apache POI를 사용하여 Word 문서를 이동하는 방법에 대해 알아보겠습니다.

문서 이동 기능 구현

우선 Apache POI의 XWPFDocument 클래스를 사용하여 Word 문서를 로드합니다. 다음은 Word 문서를 이동하는 예제 코드입니다.

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;

import java.io.FileInputStream;

public class DocumentMover {
    public static void main(String[] args) {
        try {
            // 원본 Word 문서 로드
            FileInputStream file = new FileInputStream("original.docx");
            XWPFDocument document = new XWPFDocument(file);

            // 이동할 문단 선택
            XWPFParagraph paragraphToMove = document.getParagraphArray(0);

            // 문단 이동
            document.removeBodyElement(0);
            document.setParagraph(paragraphToMove, 1);

            // 이동된 문서 저장
            document.write(new FileOutputStream("moved.docx"));

            // 리소스 정리
            file.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

위의 코드에서는 original.docx라는 원본 Word 문서를 로드한 후, 첫 번째 문단을 선택하여 이동시킵니다. 그리고 moved.docx라는 새로운 파일에 이동된 문서를 저장합니다.

XWPFDocument 클래스의 removeBodyElement 메서드를 사용하여 문서에서 원하는 문단을 삭제하고, setParagraph 메서드를 사용하여 새로운 위치에 해당 문단을 추가합니다.

정리

Apache POI를 사용하여 Java에서 Word 문서를 이동하는 방법에 대해 알아보았습니다. 이 예제를 통해 Apache POI의 기본적인 사용법과 문서 조작 기능에 대해 익힐 수 있습니다. 추가로 필요한 기능이 있다면 Apache POI 공식 문서를 참조하시기 바랍니다.

참고 자료