-
[Docx4j] 문자열 치환으로 간편한 문서 만들기JAVA/LIBRARY 2014. 7. 22. 09:37728x90
2014년 7월 개인 프로젝트로 보고서 작성을 위해 간편하게 문자열 치환으로 보고서를 만드는 library를 생각하고 80% 정도(POI를 이용하여서 크게 어렵지 않았다.) 만들었을때, http://www.docx4java.org/trac/docx4j 사이트를 보게 되었다. 내가 만들려고 하던 것이 이미 구현 되어 있었기 때문에 과감하게 만들던 library는 접고 개인 프로젝트에 docx4j를 사용하였다. 사용법을 간단하게 정리 한다.
docxj4에서는 많은 기능을 제공한다. 그 중 이번 개인 프로젝트에서 사용한 문자열 치환하는 샘플 소스 이다.
public class VariableReplace { public static void main(String[] args) throws Exception { // Exclude context init from timing org.docx4j.wml.ObjectFactory foo = Context.getWmlObjectFactory(); // Input docx has variables in it: ${colour}, ${icecream} String inputfilepath = System.getProperty("user.dir") + "/sample-docs/word/unmarshallFromTemplateExample176.docx"; boolean save = false; String outputfilepath = System.getProperty("user.dir") + "/OUT_VariableReplace.docx"; WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage .load(new java.io.File(inputfilepath)); MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); HashMap<string, string> mappings = new HashMap<string, string>(); mappings.put("colour", "green"); mappings.put("icecream", "chocolate"); long start = System.currentTimeMillis(); // Approach 1 (from 3.0.0; faster if you haven't yet caused unmarshalling to occur): documentPart.variableReplace(mappings); /* // Approach 2 (original) // unmarshallFromTemplate requires string input String xml = XmlUtils.marshaltoString(documentPart.getJaxbElement(), true); // Do it... Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings); // Inject result into docx documentPart.setJaxbElement((Document) obj); */ long end = System.currentTimeMillis(); long total = end - start; System.out.println("Time: " + total); // Save it if (save) { SaveToZipFile saver = new SaveToZipFile(wordMLPackage); saver.save(outputfilepath); } else { System.out.println(XmlUtils.marshaltoString(documentPart.getJaxbElement(), true, true)); } } }
상위 소스를 보면 참 쉽줘~ 라는 말이 나올수 밖에 없다.
상위 소스는 docx4j 에서 받을 수 있다.
간단하게 설명을 하면, docx 문서에서 치환할 위치에 ${KEY}로 문서 내용을 적고 java 에서 HashMap 으로 KEY 와 VALUE를 준비해서 documentPart.variableReplace(mappings); 만 호출 해주면 끗!
추가로 https://code.google.com/p/xdocreport/ 이것도 있다
아는분 조언에 따르면 xdocreport가 사용이 편하다고 한다.
728x90'JAVA > LIBRARY' 카테고리의 다른 글
Srping Batch Meta 정보를 조회하는 기능입니다. (0) 2021.06.28 다른 위치의 DB 테이블 복사 기능 만들기 (0) 2017.10.27 [벤치 마크 라이브러리]JMH (0) 2016.01.26 [Lombok]사용 설명 (0) 2015.07.21 [easyExcelMaker] 쉽게 만드는 Excel (0) 2014.07.22