본문 바로가기

Programming/과거포스팅

JSP POI MS Word CREATE( POI MS WORD 다운로드)

프로젝트 진행중 급하게 ms 워드 문서를 생성해서 다운로드 해야 하는 기능이 생겼다.

엑셀은 샘플 코드가 많지만 워드관련 자료는 많지 않았다.

급하게 만드느라 다양한 기능을 넣지는 못했지만. 텍스트와 하이퍼링크 삽입이 가능한 코드다.

하이퍼 링크는 외국사이트에서 가져왔는데 아직 다듬지는 않았다.

추후 디테일한 문서를 만들면서 쓸만한 api를 찾아서 포스팅하겠다.

질문은 댓글로..


package com.web.document; import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.xwpf.usermodel.ParagraphAlignment; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRelation; import org.apache.poi.xwpf.usermodel.XWPFRun; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTHyperlink; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText; import com.web.common.CommonUtil; public class WordWriteModule { public static void wordWrite(HttpServletResponse response, JSONArray jsonArray){ try { response.setContentType("application/octet-stream"); //완성된 워드를 다운로드 해야하니 outputStream을 response 객체에서 가져옴 response.setHeader("Content-Disposition", "attachment; filename=sample.docx;"); OutputStream outputStream = response.getOutputStream(); XWPFDocument xwpfDocument = new XWPFDocument(); //도큐먼트를 생성 XWPFParagraph xwpfParagraph = xwpfDocument.createParagraph(); xwpfParagraph.setAlignment(ParagraphAlignment.CENTER); XWPFRun xwpfRun = xwpfParagraph.createRun(); xwpfRun.setBold(true); xwpfRun.setFontSize(20); xwpfRun.setText("제목"); if ( CommonUtil.objectNullCheck(jsonArray)) { for ( int i=0; i < jsonArray.size(); i++) { JSONObject jsonObject = (JSONObject) jsonArray.get(i); //데이터를 jsonObject로 가져왔다. 컬렉션은 원하는 자료구조로.. XWPFParagraph xwpfParagraphDate = xwpfDocument.createParagraph(); xwpfParagraphDate.setAlignment(ParagraphAlignment.LEFT); xwpfParagraphDate.setSpacingAfterLines(1); //줄바꿈시 다음줄까지의 공간 XWPFRun xwpfRunDate = xwpfParagraphDate.createRun(); xwpfRunDate.addBreak(); //줄바꿈 xwpfRunDate.setFontSize(10); xwpfRunDate.setText((String)jsonObject.get("date")); XWPFParagraph xwpfParagraphTitle = xwpfDocument.createParagraph(); xwpfParagraphTitle.setAlignment(ParagraphAlignment.LEFT); xwpfParagraphTitle.setSpacingAfterLines(1); appendExternalHyperlink((String)jsonObject.get("link"), (String)jsonObject.get("title_org"), xwpfParagraphTitle); XWPFRun xwpfRunTitle = xwpfParagraphTitle.createRun(); xwpfRunTitle.setBold(true); xwpfRunTitle.setFontSize(10); xwpfRunTitle.setText("["+ jsonObject.get("author") +"]"); XWPFParagraph xwpfParagraphContent = xwpfDocument.createParagraph(); xwpfParagraphContent.setAlignment(ParagraphAlignment.LEFT); xwpfParagraphContent.setSpacingAfterLines(1); XWPFRun xwpfRunContent = xwpfParagraphContent.createRun(); xwpfRunContent.setFontSize(10); xwpfRunContent.setText((String)jsonObject.get("content_org")); } } xwpfDocument.write(outputStream); outputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static void appendExternalHyperlink(String url, String text, XWPFParagraph paragraph){ //하이퍼링크(Hyperlink) //Add the link as External relationship String id = paragraph.getDocument().getPackagePart().addExternalRelationship(url, XWPFRelation.HYPERLINK.getRelation()).getId(); //Append the link and bind it to the relationship CTHyperlink cLink = paragraph.getCTP().addNewHyperlink(); cLink.setId(id); //Create the linked text CTText ctText = CTText.Factory.newInstance(); ctText.setStringValue(text); CTR ctr = CTR.Factory.newInstance(); ctr.setTArray(new CTText[]{ctText}); //Insert the linked text into the link cLink.setRArray(new CTR[]{ctr}); } }