엑셀파일 생성 후 다운로드 ( java, Spring 환경) 예제

 

FileDownloadView.java 파일

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.FileCopyUtils;
import org.springframework.web.servlet.view.AbstractView;

public class FileDownloadView extends AbstractView{

	public FileDownloadView(){
        //content type을 지정. 
        setContentType("apllication/download; charset=utf-8");
    }
	
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model,
        HttpServletRequest req, HttpServletResponse res) throws Exception {

        File file = (File) model.get("downloadFile");

        res.setContentType(getContentType());
        res.setContentLength((int) file.length());
        res.setHeader("Content-Disposition", "attachment; filename=\"" + 
                java.net.URLEncoder.encode(file.getName(), "utf-8") + "\";");
        res.setHeader("Content-Transfer-Encoding", "binary");

        OutputStream out = res.getOutputStream();
        FileInputStream fis = null;

        try {
            fis = new FileInputStream(file);
            FileCopyUtils.copy(fis, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(fis != null) {
                try { 
                    fis.close(); 
                }catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        out.flush();
    }
}

 

mvc-config.xml

<bean id="fileDownloadView" class="my.projectname.common.util.FileDownloadView"/>

 

LinkController.java 

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFColor;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping(value = "/link")
public class LinkController {

	private static final Logger LOGGER = Logger.getLogger(LinkController.class);
	
	//----------------------------------------------------------
    //추가 - Properties값 읽어오기
    //----------------------------------------------------------
    @Value("#{projectline['server_type']}")
    private String serverType;
    
    @Value("#{projectline['file.upload.path']}")
    private String fileUploadPath;
    
    @RequestMapping(value = "/getExcelDown.do", method = RequestMethod.GET)  // , method = RequestMethod.POST  지우면 GET/POST 모두 가능 
    @ResponseBody
    public ModelAndView getExcelDown(HttpServletRequest request) {
    	String contentid = request.getParameter("contentid");
    	String classid = request.getParameter("classid");
    	LOGGER.debug("@@@getExcelDown, contentid = "+contentid+", classid="+classid); // 값을 안넣으면 null 값 옴.
    	//.xlsx 확장자 지원 
    	XSSFWorkbook xssfWb = null; 
    	XSSFSheet xssfSheet = null; 
    	XSSFRow xssfRow = null;
    	XSSFCell xssfCell = null;
    	File tempFile = null;
 		String uploadFilePath = fileUploadPath+"content_"+contentid+".xlsx";
 		
    	try { 
    		int rowNo = 0; // 행의 갯수 
    		xssfWb = new XSSFWorkbook(); //XSSFWorkbook 객체 생성 
    		xssfSheet = xssfWb.createSheet("워크 시트1"); // 워크시트 이름 설정 
    		// 폰트 스타일 
    		XSSFFont font = xssfWb.createFont(); 
    		font.setFontName(HSSFFont.FONT_ARIAL); // 폰트 스타일 
    		font.setFontHeightInPoints((short)20); // 폰트 크기 
    		font.setBold(true); // Bold 설정 
    		XSSFColor myColor = new XSSFColor();
    		myColor.setARGBHex("FF0077FF");
    		font.setColor(myColor); // 폰트 색 지정 
    		//테이블 셀 스타일 
    		CellStyle cellStyle = xssfWb.createCellStyle(); 
    		xssfSheet.setColumnWidth(0, (xssfSheet.getColumnWidth(0))+(short)2048); // 0번째 컬럼 넓이 조절 
    		cellStyle.setFont(font); // cellStyle에 font를 적용 
    		cellStyle.setAlignment(HorizontalAlignment.CENTER); // 정렬 
    		//셀병합 
    		xssfSheet.addMergedRegion(new CellRangeAddress(0, 1, 0, 4)); //첫행, 마지막행, 첫열, 마지막열 병합 // 타이틀 생성 
    		xssfRow = xssfSheet.createRow(rowNo++); // 행 객체 추가 
    		xssfCell = xssfRow.createCell((short) 0); // 추가한 행에 셀 객체 추가 
    		xssfCell.setCellStyle(cellStyle); // 셀에 스타일 지정 
    		xssfCell.setCellValue("타이틀 입니다"); // 데이터 입력 
    		xssfSheet.createRow(rowNo++); 
    		xssfRow = xssfSheet.createRow(rowNo++); // 빈행 추가 //테이블 스타일 설정 
    		CellStyle tableCellStyle = xssfWb.createCellStyle(); 
    		tableCellStyle.setBorderTop(BorderStyle.MEDIUM_DASHED); // 테두리 위쪽 
    		tableCellStyle.setBorderBottom(BorderStyle.MEDIUM_DASHED); // 테두리 아래쪽 
    		tableCellStyle.setBorderLeft(BorderStyle.MEDIUM_DASHED); // 테두리 왼쪽 
    		tableCellStyle.setBorderRight(BorderStyle.MEDIUM_DASHED); // 테두리 오른쪽 
    		xssfRow = xssfSheet.createRow(rowNo++); 
    		xssfCell = xssfRow.createCell((short) 0); 
    		xssfCell.setCellStyle(tableCellStyle);
    		xssfCell.setCellValue("셀1"); 
    		xssfCell = xssfRow.createCell((short) 1); 
    		xssfCell.setCellStyle(tableCellStyle); 
    		xssfCell.setCellValue("셀2"); 
    		xssfCell = xssfRow.createCell((short) 2); 
    		xssfCell.setCellStyle(tableCellStyle); 
    		xssfCell.setCellValue("셀3"); 
    		xssfCell = xssfRow.createCell((short) 3); 
    		xssfCell.setCellStyle(tableCellStyle); 
    		xssfCell.setCellValue("셀4"); 
    		xssfCell = xssfRow.createCell((short) 4); 
    		xssfCell.setCellStyle(tableCellStyle); 
    		
      		tempFile = new File(uploadFilePath);
    		tempFile.deleteOnExit();   // JVM종료시 파일 삭제 (서버 재시작시 삭제됨)
    		FileOutputStream fos = null; 
    		fos = new FileOutputStream(tempFile); 
    		xssfWb.write(fos); 
    		if (fos != null) fos.close(); 

        	return new ModelAndView("fileDownloadView", "downloadFile", tempFile);
        	
		}catch(Exception e){ 
			e.printStackTrace();
		}

    }
    	
}

 

http://localhost:8080/link/getExcelDown.do?contentid=100200

 

이런식으로 브라우져 주소창에 입력하면 엑셀샘플파일을 다운로드 할 수 있다.

 

interceptor-config.xml 에서 추가 설정이 필요하다.

<mvc:exclude-mapping path="/link/**"/>

 

 

 

+ Recent posts