티스토리 뷰

1. 평소 인터넷에서 사용하는 것처럼 다운창(경로지정하는 창)을 띄워서 하는 방법이다.

조낸 애먹었다.. 완성해보니 해보니 해볼만 하다는 생각도 들지만..젠장.

샘플하나없이 인터넷만 보고 하느라 몇일이 걸렸다..나는 바보인가.ㅠㅠ



<%@ page language="java" contentType="text/html;charset=UTF-8" pageEncoding="UTF-8"%>


<%@ page import="categoryrank.common.CategoryConfig" %>

<%@ page import="categoryrank.data.*  " %> 

<%@ page import="categoryrank.logic.* " %>

<%@ page import="categoryrank.common.CommonUtil" %>

<%@ page import="java.io.OutputStream" %>

<%@ page import="java.util.ArrayList" %>


<%@ page import="org.apache.poi.hssf.usermodel.HSSFCellStyle" %>

<%@ page import="org.apache.poi.hssf.usermodel.HSSFRow" %>

<%@ page import="org.apache.poi.hssf.usermodel.HSSFSheet" %> 

<%@ page import="org.apache.poi.hssf.usermodel.HSSFWorkbook" %> 

<%@ page import="org.apache.poi.hssf.util.HSSFColor" %>

<%@ page import="org.apache.poi.ss.usermodel.Cell" %>


<%@ page import="categoryrank.common.CommonUtil" %>


<jsp:useBean id="srchParam" class="categoryrank.data.CateParameterVO" scope="request" />


<!-- getParameter.jsp include 내용 삽입 -->

<!-- getParameter.jsp를  jsp:include flush="true" page= "./inc/getParameter.jsp"를 사용하여 인클루드시 out.clear 부분에서 서버버그로 인한 에러 발생 -->

<%

request.setCharacterEncoding("euc-kr"); 


srchParam.setKind(CommonUtil.null2str(request.getParameter("kind") ,""));

srchParam.setKeyword(CommonUtil.null2str(request.getParameter("keyword") ,"").trim().toLowerCase())  ;

srchParam.setCategoryCode1(CommonUtil.null2str(request.getParameter("category_01") ,""));

srchParam.setCategoryCode2(CommonUtil.null2str(request.getParameter("category_02") ,""));

srchParam.setCategoryCode3(CommonUtil.null2str(request.getParameter("category_03") ,""));

srchParam.setCategoryCode4(CommonUtil.null2str(request.getParameter("category_04") ,""));

srchParam.setCategoryName1(CommonUtil.null2str(request.getParameter("category_01_name") ,""));

srchParam.setCategoryName2(CommonUtil.null2str(request.getParameter("category_02_name") ,""));

srchParam.setCategoryName3(CommonUtil.null2str(request.getParameter("category_03_name") ,""));

srchParam.setCategoryName4(CommonUtil.null2str(request.getParameter("category_04_name") ,""));

//카테고리랭킹 STOP 유무 (Y / N)

srchParam.setStopflag(CommonUtil.null2str(request.getParameter("stopflag") ,"N"));


int depth = 0;

String mycode = "";

if (srchParam.getCategoryCode4().length() > 0)

{

mycode = srchParam.getCategoryCode4();

depth = 4;

}else if (srchParam.getCategoryCode3().length() > 0)

{

mycode = srchParam.getCategoryCode3();

depth = 3;

}else if (srchParam.getCategoryCode2().length() > 0)

{

mycode = srchParam.getCategoryCode2();

depth = 2;

}else if (srchParam.getCategoryCode1().length() > 0)

{

mycode = srchParam.getCategoryCode1();

depth = 1;

}

srchParam.setCategoryCode(mycode);

srchParam.setDepth(depth);

%>

별로 중요한 부분도 아닌데 왜 색깔을 칠해놨을까..

왜냐..이부분을 <jsp:include flush="true" page= "./inc/getParameter.jsp" /> 이런식으로 include를 사용해서 하면 안된다.

이유는 하단의 out.clear(); 부분에서 오류가 발생한다.

해보면 안다.

<!-- getParameter.jsp include 내용 삽입 끝-->


<%

java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss");

String today = formatter.format(new java.util.Date());

String filename = "";

String check = srchParam.getStopflag(); //반영단어/금지단어 구분

if(check.equals("N")){

filename = "ApplyList"+today;

}else{

filename = "StopList"+today;

}

    response.setContentType("application/octet-stream");

    response.setHeader("Content-Disposition", "attachment; filename="+filename+".xls;");


    // 파일 이름은 한글로하면 오류가 발생한다.

    

    ArrayList result = null;

ExcelExport exTest = new ExcelExport();

CategoryRank objCaterank = new CategoryRank();

String dbinfo = CategoryConfig.getDbinfo();

String id = CategoryConfig.getDbuserid();

String pass = CategoryConfig.getDbpassword();

int total    = 0;

//연결

objCaterank.connect(dbinfo,id,pass);

String mode = CommonUtil.null2str(request.getParameter("mode"), "");

String rowid = CommonUtil.null2str(request.getParameter("rowid"), "");


if( "del".equals(mode) && rowid.length() > 0 ) {

objCaterank.deleteRow(rowid);

}

total  = objCaterank.getTotal ( objCaterank.makeCategorySql(srchParam) ); 

result = objCaterank.selectRow( objCaterank.makeExcelCategorySql(srchParam) );

categoryrank.data.CateParameterVO fdata = null;

try{

HSSFWorkbook wb = new HSSFWorkbook(); //워크북을 만들고

HSSFSheet sheet = wb.createSheet("sheet1"); //시트이름은 한글도 가능하다.

sheet = CreateSheetData(result, check, wb, sheet);//위에서 구현한 엑셀함수를 호출한다.

 

out.clear();

out = pageContext.pushBody();

OutputStream xlsOut = response.getOutputStream(); //OutputStream으로 엑셀을 저장한다.

wb.write(xlsOut);

xlsOut.close();

} catch ( Exception ex ) {

ex.printStackTrace(System.out);

%>






<%!

public HSSFSheet CreateSheetData(ArrayList result, String check, HSSFWorkbook wb, HSSFSheet sheet){

   

   ArrayList<String> Header = new ArrayList<String>(); //헤더생성

   

   HSSFRow row = null;

   

   row = sheet.createRow((short)0);

   

   Header.add("키워드"); 

   Header.add("대 카테고리"); 

   Header.add("중 카테고리"); 

   Header.add("소 카테고리"); 

   Header.add("세 카테고리"); 

   Header.add("전시여부");

   Header.add("등록날짜"); 

   

  

   //header style

   HSSFCellStyle Hstyle = wb.createCellStyle();

   

   Hstyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); //헤더 배경색

   Hstyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //채움

   Hstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

   Hstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   Hstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);

   Hstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   Hstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

   Hstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   Hstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);

   Hstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   

   //header 내용 및 style 적용

   for(int k=0;k<7;k++){

       Cell headerCell = row.createCell(k);

       headerCell.setCellValue(Header.get(k));

       headerCell.setCellStyle(Hstyle);

   }

   

   //content style - 셀 라인 그리기

   HSSFCellStyle Cstyle = wb.createCellStyle();

   Cstyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);

   Cstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   Cstyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);

   Cstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   Cstyle.setBorderRight(HSSFCellStyle.BORDER_THIN);

   Cstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   Cstyle.setBorderTop(HSSFCellStyle.BORDER_THIN);

   Cstyle.setBottomBorderColor(HSSFColor.BLACK.index);

   

   categoryrank.data.CateParameterVO fdata = null;

   

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

    row = sheet.createRow((short)i+1);  // sheet에 row 생성 - 0번째 행에는 header를 삽입했으므로 1번째 행부터 삽입한다. 따라서 j+1

   

    fdata = (categoryrank.data.CateParameterVO)result.get(i);

    for(int j=0; j<7; j++){

   

        Cell c = row.createCell(j);

        if(j==0){

        if(fdata.getKeyword() == null || fdata.getKeyword() == ""){

        c.setCellValue("");

        }else{        

        c.setCellValue(fdata.getKeyword());

        }

        }else if(j==1){

        String cate1 = CommonUtil.null2str(fdata.getCategoryName1(),"")

+(fdata.getCategoryCode1()!= null ? "("+fdata.getCategoryCode1()+")" : "");                

        c.setCellValue(cate1);

        }else if(j==2){

        String cate2 = CommonUtil.null2str(fdata.getCategoryName2(),"")

+(fdata.getCategoryCode2()!= null ? "("+fdata.getCategoryCode2()+")" : "");

        c.setCellValue(cate2);

        }else if(j==3){

        String cate3 = CommonUtil.null2str(fdata.getCategoryName3(),"")

+(fdata.getCategoryCode3()!= null ? "("+fdata.getCategoryCode3()+")" : "");

        c.setCellValue(cate3);

        }else if(j==4){

        String cate4 = CommonUtil.null2str(fdata.getCategoryName4(),"")

+(fdata.getCategoryCode4()!= null ? "("+fdata.getCategoryCode4()+")" : "");

        c.setCellValue(cate4);

        }else if(j==5){

        String display_cd = CommonUtil.null2str(fdata.getDisplay_cd(),"");

        c.setCellValue(display_cd);

        }else{

        c.setCellValue(fdata.getRegDate().substring(0, 11));

        }

        c.setCellStyle(Cstyle); //셀스타일 적용

       

    }        

   }

   for(int i=0;i<7;i++){

    sheet.autoSizeColumn(i); //cell 크기 자동 맞춤

  }

이 부분 완전 중요하다!! 뭣도 모르고 처음에 바로위에 for문에 넣어서 엑셀 row의 갯수만큼돌려서 각 row의 컬럼마다 지정해줬다.

즉, 데이타가 엑셀에서 100줄이고 한줄당 10컬럼이면..1000번을 돌려줬다는 말이다.

그러면 망한다. 속도 최악임. 나중에 알고보니 이부분은 속도가 느려서 딱 컬럼의 갯수만큼만 돌려주는게 좋다.

엑셀에서 한줄당 컬럼이 10개면 지금의 소스처럼 for문을 하나더 만들어서 이것만 10번 딱 돌려주길.

안그러면 내 경험으로 1500건 이상 넘어가면 1초에 1줄씩 씌어진다. 더많으면 더느려지겟지..

네이버 지식인에 물어봐서 알아냈다.

   

   java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yyyyMMddHHmmss");

String today = formatter.format(new java.util.Date());

String file_name = "";

if(check.equals("N")){

file_name = "applylist"+today;

}else{

file_name = "stoplist"+today;

}

return sheet;

}

%>