ÃֽŠ°Ô½Ã±Û(JAVA)
2020.09.21 / 11:13

Jqgrid Excel export

XMaLL°ü¸®ÀÚ
Ãßõ ¼ö 161

Jqgrid Excel export using Spring + Jakarta POI


1. JSP

<script type="text/javascript">

//È­¸é ·Îµå ½Ã Á¶È¸

function doOnLoadQuery(){

//jqGrid ¼¼ÆÃ

var grid = $('#WPCP16002_Grid');

grid.clearGridData();

grid.jqGrid({

url:'/WPC/P16/WPCP16002_tab1_popup_dtl_list.do',

datatype: "json",

jsonReader: {repeatitems : false},

        colNames:['È£¼±', 'PEºí·Ï', '2Â÷ PE', '1Â÷ PE', 'BLOCK', 'BLOCK<br>TYPE', 'ÆÀ'

                  ,'Âø¼ö','¿Ï·á', 'Âø¼ö','¿Ï·á', 'Áö¿¬ÀÏ', '¿Ï·áÁÖÂ÷'],

        colModel: [ //µ¥ÀÌÅÍ ¸ÅÇÎ ¹× ·Î¿ì ¼Ó¼º

          {name:'project_code' ,index:'project_code' ,width:60  ,align:"center"},

          {name:'pe_blk'       ,index:'pe_blk'       ,width:80  ,align:"center"},

          {name:'sec_blk'      ,index:'sec_blk'      ,width:80  ,align:"center"},

          {name:'first_blk'    ,index:'first_blk'    ,width:80  ,align:"center"},

          {name:'blk_no'       ,index:'blk_no'       ,width:80  ,align:"center"},

          {name:'blk_type'     ,index:'blk_type'     ,width:80  ,align:"center"},

          {name:'work_nm'      ,index:'work_nm'      ,width:80  ,align:"center"},

          {name:'ps_dt'        ,index:'ps_dt'        ,width:80  ,align:"center"},

          {name:'pf_dt'        ,index:'pf_dt'        ,width:80  ,align:"center"},

          {name:'ts_dt'        ,index:'ts_dt'        ,width:80  ,align:"center"},

          {name:'tf_dt'        ,index:'tf_dt'        ,width:80  ,align:"center"},

          {name:'delay_day'    ,index:'delay_day'    ,width:70  ,align:"center"},

          {name:'txn_week'     ,index:'txn_week'     ,width:60  ,align:"center"}

          ],

      //caption: 1,

      pager: "#pagingBar",

      rowList: [],

      pgbuttons: false,

      pgtext: null,

      viewrecords: false,

      rowNum:-1,

      //loadonce : true,

      height:'500',

      gridview:true,

      shrinkToFit:false,

      viewrecords:false,

      loadError: function (jqXHR, textStatus, errorThrown) {

          $("#WPCP16002_Grid").html(jqXHR.responseText);

      },

      postData:{

       radio_tp : $('#radio_tp').val(),

  fr_dt    : $('#fr_dt').val(),

  to_dt    : $('#to_dt').val(),

  team     : $('#team').val(),

  team_nm  : $('#team_nm').val(),

  proj_no  : $('#proj_no').val(),

  },

      loadComplete: function (data) {

       

          },

          gridComplete: function () {

         //õ´ÜÀ§ ±¸ºÐÀÚ ³Ö±â

           var len, point, str, countRow;

           countRow = $("#WPCP16002_Grid").getGridParam("records") + "";

              point = countRow.length % 3

              len = countRow.length;

              str = countRow.substring(0, point);

              while (point < len) {

                  if (str != "") str += ",";

                  str += countRow.substring(point, point + 3);

                  point += 3;

              }

           $('#totalRows').text('ÃÑ: '+ str +' °Ç');

          }

    });

    

    //Header Grouping

    grid.jqGrid('setGroupHeaders', {

  useColSpanStyle: true, 

  groupHeaders:[

{startColumnName: 'ps_dt', numberOfColumns: 2, titleText: '°èȹ'},

{startColumnName: 'ts_dt', numberOfColumns: 4, titleText: '½ÇÀû'}

  ]

});

    

    // Excel Export

    grid.jqGrid('navGrid','#pagingBar', {excel:true, edit:false, add:false

     , del:false, refresh:false, search:false

    });

    grid.jqGrid('navButtonAdd','#pagingBar', {caption:"Excel DownLoad",

    onClickButton: function() {

  grid.jqGrid('excelExport', {url:'/WPC/P16/WPCP16002_tab1_popup_dtl_excelView.do'});

    }});

    

grid.trigger("reloadGrid");

}

</script>


<div id="WPCP16002_Div">

<table summary="Á¶È¸ ¸®½ºÆ®" id="WPCP16002_Grid"></table>

<div id="pagingBar"></div>

</div>



2. Java controller


/**

 * ¿¢¼¿´Ù¿î·Îµå

 * @param request

 * @param response

 * @param model

 * @return

 * @throws Exception

 */

@SuppressWarnings("static-access")

@RequestMapping(value = "/WPC/P16/WPCP16002_tab1_popup_dtl_excelView.do")

public ModelAndView WPCP16002_tab1_popup_dtl_list_excel(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws Exception {

HashMap<String, Object> paraMap = new RequestUtil().paramToHashMap(request);

HashMap<String, Object> resultMap = new HashMap<String, Object>();

try {

//1. Excel sheet name

String sheetName = "¼±ÇàÁ÷Á¾ °øÁ¤ÇöȲ";

String sheetStyle = "normal";

//2. Excel sheet title(¸ñ·Ï)

List<String> title = new ArrayList<String>();

title.add("È£¼±");

title.add("PEºí·Ï");

title.add("2Â÷ PE");

title.add("1Â÷ PE");

title.add("BLOCK");

title.add("BLOCK TYPE");

title.add("ÆÀ");

title.add("Âø¼ö_°èȹ");

title.add("¿Ï·á_°èȹ");

title.add("Âø¼ö_½ÇÀû");

title.add("¿Ï·á_½ÇÀû");

title.add("Áö¿¬ÀÏ");

title.add("¿Ï·á ÁÖÂ÷");

//3. Excel data Á¶È¸

paraMap.put("FIRST_TYPE", paraMap.get("radio_tp"));

paraMap.put("FRDT", paraMap.get("fr_dt"));

paraMap.put("TODT", paraMap.get("to_dt"));

paraMap.put("TEAM_NM", paraMap.get("team"));

paraMap.put("PROJ_NO", paraMap.get("proj_no").equals("") ? "" : Arrays.asList(((String) paraMap.get("proj_no")).split(",")));

List<WPCP16001_ExcelVO> list = wPCP16002Service.selectWPCP16002_tab1_popup_list_excel(paraMap);

//4. ExcelDownView·Î µ¥ÀÌÅ͸¦ ³Ñ°ÜÁÖ±â À§ÇÑ ÀÛ¾÷

Map map;

List excelList = new ArrayList();

for(int i = 0; i < list.size(); i++)

{

//titleÀÇ ¸ñ·Ï°ú µ¿ÀÏÇÏ°Ô ±¸¼º

map = new HashMap();

map.put(title.get(0).toString(), list.get(i).getProject_code());

map.put(title.get(1).toString(), list.get(i).getPe_blk());

map.put(title.get(2).toString(), list.get(i).getSec_blk());

map.put(title.get(3).toString(), list.get(i).getFirst_blk());

map.put(title.get(4).toString(), list.get(i).getBlk_no());

map.put(title.get(5).toString(), list.get(i).getBlk_type());

map.put(title.get(6).toString(), list.get(i).getWork_nm());

map.put(title.get(7).toString(), list.get(i).getPs_dt());

map.put(title.get(8).toString(), list.get(i).getPf_dt());

map.put(title.get(9).toString(), list.get(i).getTs_dt());

map.put(title.get(10).toString(), list.get(i).getTf_dt());

map.put(title.get(11).toString(), list.get(i).getDelay_day());

map.put(title.get(12).toString(), list.get(i).getTxn_week());

excelList.add(map);

}

//5. HashMap¿¡ ´ã¾Æ ModelAndView ¸®ÅÏÇÒ ¶§ ¸ðµÎ ÇÔ²² ´ã¾Æ¼­ º¸³¿

resultMap.put("sheetNm", sheetName);

resultMap.put("sheetSt", sheetStyle);

resultMap.put("Title", title);

resultMap.put("ListExcelDown", excelList);

System.out.println("==============================================");

System.out.println("ExcelDown Controller ³¡");

System.out.println("==============================================");

} catch(Exception e) {

e.printStackTrace();

}

return new ModelAndView("ExcelDownView","ListExcelDownMap" ,resultMap);

}



3. ExcelDownView.java

package egovframework.com.cmm;


import java.util.HashMap;

import java.util.List;

import java.util.Map;


import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;


import org.apache.poi.hssf.usermodel.HSSFCell;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;

import org.apache.poi.hssf.usermodel.HSSFFont;

import org.apache.poi.hssf.usermodel.HSSFSheet;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import org.apache.poi.hssf.util.HSSFColor;

import org.apache.poi.hssf.util.CellRangeAddress;

import org.springframework.web.servlet.view.document.AbstractExcelView;


/**

 * @author

 * @function Excel DownLoad

 * @search Spring AbstractExcelView, Spring + Jakarta POI

 */

public class ExcelDownView extends AbstractExcelView {


@Override

protected void buildExcelDocument(Map<String, Object> model,

HSSFWorkbook workbook, HttpServletRequest request,

HttpServletResponse response) throws Exception {

// TODO Auto-generated method stub

HSSFCell cell = null;

int idx = 0;

int cnt = 0;

//1. °¢°¢ÀÇ controller¿¡¼­ ¸¶Áö¸·¿¡ ³Ñ±ä ModelAndView °¡Á®¿È

Map<String, Object> map = (Map<String, Object>) model.get("ListExcelDownMap");

//2. ½ÃÆ®À̸§ ¼³Á¤

String sheetName = (String) map.get("sheetNm");

String sheetStyle = (String) map.get("sheetSt");//½ÃÆ® ½ºÅ¸ÀÏ ¼³Á¤

//3. ¿¢¼¿ÆÄÀÏ »ý¼º

HSSFSheet sheet = workbook.createSheet(sheetName);

cell = getCell(sheet, 0, 0);

setText(cell, sheetName);//½ÃÆ®(0, 0)¼¿¿¡ Á¦¸ñ°ú °°Àº ÅؽºÆ® ¼¼ÆÃ

//¼¿º´ÇÕ 

sheet.addMergedRegion(new CellRangeAddress(

                  0, //½ÃÀÛ Çà¹øÈ£

                  0, //¸¶Áö¸· Çà¹øÈ£

                  0, //½ÃÀÛ ¿­¹øÈ£

                  5  //¸¶Áö¸· ¿­¹øÈ£

));

idx = 0;

//4. Ä÷³Á¦¸ñ ¹× »ö¼¼ÆÃ

List<Object> titleList = (List<Object>) map.get("Title");

//¼¿ ÆùÆ® & ½ºÅ¸ÀÏ Ãß°¡

HSSFCellStyle CellStyle = workbook.createCellStyle();

CellStyle.setFillBackgroundColor(HSSFColor.LIGHT_GREEN.index);

CellStyle.setFillPattern(HSSFCellStyle.ALIGN_CENTER);

HSSFFont font = workbook.createFont();

font.setColor(HSSFColor.RED.index);

//¿¢¼¿ »ó´ÜÁ¦¸ñ¼¼ÆÃ

if(sheetStyle.equals("normal")) {

for(int i = 0; i < titleList.size(); i++) {

    setText(getCell(sheet, 2, idx++), titleList.get(i).toString());

    getCell(sheet, 2, i).setCellStyle(CellStyle);

}

}

//5. Á¶È¸µÈ µ¥ÀÌÅÍ ¼¼ÆÃ

HashMap getMap = new HashMap();

List<Object> ListExcelDownList = (List<Object>) map.get("ListExcelDown");

//µ¥ÀÌÅÍ ¼¼ÆÃ

if(sheetStyle.equals("normal")) {

for (int i = 0; i < ListExcelDownList.size(); i++) {

getMap = (HashMap)ListExcelDownList.get(i);

for(int j = 0; j < titleList.size(); j++) {

cell = getCell(sheet, 3+i, j);

setText(cell, (String) getMap.get(titleList.get(j).toString()));

//sheet.autoSizeColumn((short)j);//¼¿ width ÀÚµ¿Á¶Á¤

//sheet.setColumnWidth(j, (sheet.getColumnWidth(j))+512 ); //ÀÚµ¿Á¶Á¤ ÈÄ À߸®´Â ºÎºÐÁ¶Á¤ 

}

}

//these cords have been separated from second loop(for(int j = 0; j < titleList.size(); j++)) to enhance the download speed!

for(int k=0; k < titleList.size(); k++){

sheet.autoSizeColumn((short)k);//cell width auto resize

sheet.setColumnWidth(k, (sheet.getColumnWidth(k))+512 ); //ÀÚµ¿Á¶Á¤ ÈÄ À߸®´Â ºÎºÐÁ¶Á¤

}

}

}

}




4. context-excel.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">


<bean id="excelZipService" class="egovframework.rte.fdl.excel.impl.EgovExcelServiceImpl">

<property name="mapClass" value="egovframework.com.sym.ccm.zip.service.impl.EgovCcmExcelZipMapping" />

<property name="sqlMapClient" ref="egov.sqlMapClient" />

</bean>

<bean id="excelRdnmadZipService" class="egovframework.rte.fdl.excel.impl.EgovExcelServiceImpl">

<property name="mapClass" value="egovframework.com.sym.ccm.zip.service.impl.EgovCcmExcelRdnmadZipMapping" />

<property name="sqlMapClient" ref="egov.sqlMapClient" />

</bean>

<bean id="ExcelDownView" class="egovframework.com.cmm.ExcelDownView"></bean>

<bean class="org.springframework.web.servlet.view.BeanNameViewResolver">

<property name="order" value="0"></property>

</bean>

</beans>



* Issue

µ¥ÀÌÅÍ row°¡ 1000 °Ç ÀÌ»ó ³Ñ¾î°¥ °æ¿ì ´Ù¿î·Îµå ½Ã°£ ¿À·¡°É¸².

3~4000 rows Á¤µµÀÏ ¶§´Â ¹«¹ÝÀÀ ȤÀº error ¹ß»ý...

3¹ø¿¡ ExcelDownView.java ÆÄÀÏ¿¡¼­ ¿ø·¡ ÀÖ´ø Äڵ带 ¾ø¾Ö°í ¾Æ·¡·Î ¿Å±â¸é ¹®Á¦ ÇØ°á!!!~^_^


* Âü°í·Î ExcelDownView.java ¿¡¼­ ¾Æ·¡ ½ºÅ¸ÀÏÀÇ Äڵ嵵 °¡´É.

//5. Á¶È¸µÈ µ¥ÀÌÅÍ ¼¼ÆÃ

HashMap getMap = new HashMap();

List<Object> ListExcelDownList = (List<Object>) map.get("ListExcelDown");

//µ¥ÀÌÅÍ ¼¼ÆÃ

if(sheetStyle.equals("normal")) {

for (int i = 0; i < ListExcelDownList.size(); i++) {

HSSFRow excelRow = sheet.createRow(i+3);

getMap = (HashMap)ListExcelDownList.get(i);

for(int j = 0; j < titleList.size(); j++){

excelRow.createCell(j).setCellValue((String) getMap.get(titleList.get(j).toString()));

}

}

for(int k=0; k < titleList.size(); k++){

sheet.autoSizeColumn((short)k);//¼¿ width ÀÚµ¿Á¶Á¤

sheet.setColumnWidth(k, (sheet.getColumnWidth(k))+512 ); //ÀÚµ¿Á¶Á¤ ÈÄ À߸®´Â ºÎºÐÁ¶Á¤

}

[Ãâó] Jqgrid Excel export|ÀÛ¼ºÀÚ hemiblue