본문 바로가기

Java

Excel download & upload

excel 라이브러리 종류 poi , jxl

엑셀다운받을대는 poi <--대용량속도가 느리지만 엑셀형태로 정확히나와 엑셀 작업하기 좋음

엑셀업로드할대는 jxl <--대용량 속도가 빠름


but 엑셀 업로드 할때 jxl은 xls만 지원되기때문에 xls,xlxs 둘다 사용할수있는 poi로 작업함


-----엑셀 다운할때---

1. ServetOutPutStream out = response.getOutPutStream();  <--에러남

에러문구: java getOutPutStream() has already been called for this response

해결방안: jsp 파일에 out.clear(); ...해주면 되는데 사용안함


2. File file = new File(filename) 로컬에서는 될지라도 웹에서 다운받는 형식이면 사용못함


3. AbstractExcelView 상속받아서 쓴다.

  좋은점이 자동으로 response 해준다. 간단하게 해결가능

주의해야할 점은 ajax로 하면 안됨..에러남 form으로 submit 해주면 된다,


---엑셀 다운 적용 소스---

<controller>

ModelAndView mav = new ModelAndView();

List orderinfoList = adminService.getorderinfoExcelList(rMap);

map.put("downsize",  orderinfoList.size());

mav.setViewName("orderInfoExcelView");

mav.addObject("orderInfoList",orderinfoList);

return mav;


<pom.xml>

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi</artifactId>

<version>3.11</version>

</dependency>

<dependency>

<groupId>org.apache.poi</groupId>

<artifactId>poi-ooxml</artifactId>

<version>3.11</version>

</dependency>


<servlet.xml>

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

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

</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

        <!-- one of the properties available; the maximum file size in bytes 10MB -->

        <property name="maxUploadSize" value="10000000"/>

</bean>


<OrderInfoExcelView>

package redshop4.admin.controller;


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.HSSFRichTextString;

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

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.ss.usermodel.Cell;

import org.apache.poi.ss.usermodel.CellStyle;

import org.apache.poi.ss.usermodel.Row;

import org.apache.poi.ss.usermodel.Sheet;

import org.apache.poi.ss.usermodel.Workbook;

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


import redshop4.order.model.OrderInfoExcel;


public class OrderInfoExcelView extends AbstractExcelView{

/**

* 생성자 

*/

public OrderInfoExcelView() {

}

@Override

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

HSSFWorkbook workbook, HttpServletRequest request,

HttpServletResponse response) throws Exception {

// TODO Auto-generated method stub

String fileName = "주문내역.xls";

String encodedFileName = new String(fileName.getBytes("euc-kr"), "8859_1"); 


List orderinfoList = (List)model.get("orderInfoList");

 // Workbook 생성 (참고: http://poi.apache.org/spreadsheet/how-to.html)

        //Workbook xlsWb = new HSSFWorkbook(); // Excel 2007 이전 버전

        //Workbook xlsxWb = new XSSFWorkbook(); // Excel 2007 이상

        //SXSSFWorkbook sxssfWb = new SXSSFWorkbook(-1); // turn off auto-flushing and accumulate all rows in memory

        //sxssfWb.setCompressTempFiles(true); // temp files will be gzipped

        // *** Sheet-------------------------------------------------

        // Sheet 생성

        HSSFSheet sheet1 = workbook.createSheet("firstSheet");

 

        // 컬럼 너비 설정

        sheet1.setColumnWidth(0, 10000);

        sheet1.setColumnWidth(9, 10000);

        // ----------------------------------------------------------

         

        // *** Style--------------------------------------------------

        // Cell 스타일 생성

        //CellStyle cellStyle = xlsWb.createCellStyle();

        // 줄 바꿈

        //cellStyle.setWrapText(false);

        //색  설정

        //cellStyle.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);

         

        HSSFRow row = null;

        HSSFCell cell = null;

        //----------------------------------------------------------

        

        int cellIndex = 0;

        if(orderinfoList != null){

        row = sheet1.createRow(0);

    row.createCell(0).setCellValue(getString("주문번호"));

    row.createCell(1).setCellValue(getString("주문일시"));

    row.createCell(2).setCellValue(getString("주문처리상태"));

    row.createCell(3).setCellValue(getString("주문자명(ID)"));

    row.createCell(4).setCellValue(getString("주문자 전화번호"));

    row.createCell(5).setCellValue(getString("주문자 이메일"));

    row.createCell(6).setCellValue(getString("수취인명"));

    row.createCell(7).setCellValue(getString("수취인 휴대전화"));

    row.createCell(8).setCellValue(getString("수취인 자택전화"));

    row.createCell(9).setCellValue(getString("배송지 우편번호"));

    row.createCell(10).setCellValue(getString("배송지 주소"));

    row.createCell(11).setCellValue(getString("배송지 요청사항"));

    row.createCell(12).setCellValue(getString("상품명"));

    row.createCell(13).setCellValue(getString("옵션"));

    row.createCell(14).setCellValue(getString("수량"));

    row.createCell(15).setCellValue(getString("상품별금액"));

    row.createCell(16).setCellValue(getString("구매금액"));

    row.createCell(17).setCellValue(getString("사용적립금"));

    row.createCell(18).setCellValue(getString("배송비"));

    row.createCell(19).setCellValue(getString("총결제금액"));

    row.createCell(20).setCellValue(getString("결제방법"));

    row.createCell(21).setCellValue(getString("결제상태"));

    row.createCell(22).setCellValue(getString("결제메모"));

    row.createCell(23).setCellValue(getString("배송업체"));

    row.createCell(24).setCellValue(getString("송장번호"));

   

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

        cellIndex = 0; //초기화

       

        OrderInfoExcel orderInfoExcel = (OrderInfoExcel)orderinfoList.get(i);

        //줄

        row = sheet1.createRow((i+1));

        //셀--------------------------------------------

        // 0 주문번호

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getOrdernumber()));


// 1 주문일시

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getWritedate()));


// 2 주문처리상태

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getStatus_text()));


// 3 주문자명

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getOrdername()));


// 4 주문자 전화번호

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getOrderphone()));


// 5 주문자 이메일

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getOrderemail()));


// 6 수취인명

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getRecipientname()));


// 7 휴대전화

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getRecipientcelphone()));


// 8 자택전화

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getRecipientphone()));


// 9 배송지 우편번호

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getDeliveryzipcode()));


// 10 배송지 주소

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getDeliveryaddress()));


// 11 배송 요청사항

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getDeliverymemo()));

// 12 상품명

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getName()));

// 13 상품옵션

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getOptionItems()));

// 14  수량

cell = row.createCell(cellIndex++);

cell.setCellValue(orderInfoExcel.getAmount());

// 15 상품별 금액

cell = row.createCell(cellIndex++);

cell.setCellValue(orderInfoExcel.getPrice());

// 16 구매금액

cell = row.createCell(cellIndex++);

cell.setCellValue(orderInfoExcel.getTotalprice());


// 17 사용적립금

cell = row.createCell(cellIndex++);

cell.setCellValue(orderInfoExcel.getUsepoint());


// 18 배송비

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getDeliveryprice_text()));


// 19 총 결제금액

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getTotalpayment_text()));


// 20 결제방법

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getPaymenttype_text()));


// 21 결제상태

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getPaymentstatus_text()));


// 22 결제메모

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getPaymentmemo()));


// 23 배송업체

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getDeliverycompany()));


// 24 송장번호

cell = row.createCell(cellIndex++);

cell.setCellValue(getString(orderInfoExcel.getDeliverynumber()));

/*// manually control how rows are flushed to disk 

          if(i % 100 == 0) {

               ((SXSSFSheet)sheet1).flushRows(100); // retain 100 last rows and flush all others


               // ((SXSSFSheet)sh).flushRows() is a shortcut for ((SXSSFSheet)sh).flushRows(0),

               // this method flushes all rows

          }*/

       

        }

        }

        

        response.setHeader("Content-Disposition", "attachment; FileName=" + encodedFileName ); 

//response.setHeader("Content-Transfer-Encoding", "binary");

response.setContentType("application/x-msexcel");

        

//setHeaderCreateExcel(filename,request,response);

}

public void setHeaderCreateExcel(String filename,HttpServletRequest request, HttpServletResponse response){

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

        response.setContentType("application/x-msexcel");

        //response.setContentLength(fileSize);

        response.setHeader("Content-Transfer-Encoding", "binary;");

        response.setHeader("Pragma", "no-cache;");

response.setHeader("Expires", "-1;");

response.setHeader("Cache-Control", "cache, must-revalidate");

    // IE 5.5는 형식이 다르므로 헤더를 각각 다르게 처리해 준다.

  if (request.getHeader("User-Agent").indexOf("MSIE 5.5") > -1) {

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

  } else {

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

  }

}

public HSSFRichTextString getString(String str) {

return new HSSFRichTextString(str);

}


}



--엑셀 업로드할때--


@RequestMapping(value = "~~~~", method=RequestMethod.POST)

public ModelAndView orderExcelUload(HttpServletRequest request, HttpServletResponse response) {

Map<String, Object> map  = new HashMap<String, Object>();

Map<String, Object> rMap  = new HashMap<String, Object>();

String type =ServletRequestUtils.getStringParameter(request, "type","");

long currentTime     = System.currentTimeMillis();

String dir           = "/files/excel/" + Lib.getCurrentDateDir();

String filename1     = "order_"+String.valueOf(currentTime);

String msg = "";

String errMsg = "";

int successCount = 0;

int rownum = 0;

int cellnum = 0;

//엑셀파일 서버에 저장하기

String excel_file_ext = Lib.fileUploadFullExt(request,"file1",dir,filename1);

if( excel_file_ext.equals("")){

map.put("msg",  "파일이 없습니다.");

return Lib.getModelAndView(map);

}else if(excel_file_ext.equals("xls")){

rMap.put("filename",     dir+"/"+filename1+"."+excel_file_ext);

}else if(excel_file_ext.equals("xlsx")){

rMap.put("filename",     dir+"/"+filename1+"."+excel_file_ext);

}else{

map.put("msg",  "엑셀파일이 아닙니다.");

return Lib.getModelAndView(map);

}

try {


//서버에 저장된 엑셀파일 경로

String defaultDir = "";

Properties properties = new Properties();

properties.load(new FileInputStream(request

.getServletContext().getRealPath(

"/WEB-INF/classes/files.properties")));

defaultDir = properties.getProperty("defaultDir");

//filename1="order_1456972296239.xlsx";

String filePath = defaultDir + dir + "/" + filename1 +"."+excel_file_ext;

if(excel_file_ext.equals("xls")){

//xls 파일 읽기-------------------------------------------------------------

//POIFSFileSystem excel = new POIFSFileSystem(new FileInputStream(filePath));

HSSFWorkbook workBook = new HSSFWorkbook(new FileInputStream(filePath));

HSSFSheet sheet = null;

HSSFRow row = null;

HSSFCell cell = null;

sheet = workBook.getSheetAt(0); //첫 시트

rownum = sheet.getPhysicalNumberOfRows();

for(int i=1; i<rownum; i++){ //두번째 줄부터 시작

row = sheet.getRow(i); //row에 입력 된 값이 없을 경우 null을 리턴

cellnum = row.getPhysicalNumberOfCells();

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

cell = row.getCell(j);

switch(cell.getCellType()){

case 0:

System.out.println("int: " +Long.toString((long)cell.getNumericCellValue()));

break;

case 1:

System.out.println("string: "+cell.getStringCellValue());

break;

case Cell.CELL_TYPE_FORMULA:

System.out.println("cell_type: "+cell.getCellFormula());

break;

default:

System.out.println("");

}//switch end

}//cell end

}//row end

}else{

//xlsx 파일 읽기-------------------------------------------------------------

XSSFWorkbook workBook = new XSSFWorkbook(new FileInputStream(filePath));

XSSFSheet sheet = null;

XSSFRow row = null;

XSSFCell cell = null;


sheet = workBook.getSheetAt(0); //첫 시트

rownum = sheet.getPhysicalNumberOfRows();

for(int i=1; i<rownum; i++){ //두번째 줄부터 시작

row = sheet.getRow(i); //row에 입력 된 값이 없을 경우 null을 리턴

cellnum = row.getPhysicalNumberOfCells();

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

cell = row.getCell(j);

switch(cell.getCellType()){

case 0:

System.out.println("int: " +Long.toString((long)cell.getNumericCellValue()));

break;

case 1:

System.out.println("string: "+cell.getStringCellValue());

break;

case Cell.CELL_TYPE_FORMULA:

System.out.println("cell_type: "+cell.getCellFormula());

break;

default:

System.out.println("");

}//switch end

}//cell end

}//row end

}


msg = "ok";

} catch (FileNotFoundException e) {

// TODO Auto-generated catch block

errMsg = e.toString();

} catch (SQLException e) {

// TODO Auto-generated catch block

errMsg = e.toString();

} catch (IOException e) {

// TODO Auto-generated catch block

errMsg = e.toString();

}

             map.put("msg",  msg);

        

return Lib.getModelAndView(map);

}

'Java' 카테고리의 다른 글

Reflection API  (0) 2016.03.08
Collection API  (0) 2016.03.08
[error] The type BASE64Decoder is not accessible due to restriction on required library  (0) 2016.01.11
[OAuth] 인증과 권한 개념잡기  (0) 2015.10.30
google oauth2.0  (0) 2015.10.29