2012-06-27 1 views
15

apache poi를 사용하여 Excel 파일을 만들 수 있습니다. 그러나 사용자가 이것을 "진정한"Excel 파일로 다운로드 할 수 있기를 바랍니다. 달성하고자하는 효과는 사용자가 파일을 다운로드 할 수있는 팝업 상자를 갖는 것입니다. 이것은Apache POI를 사용하여 다운로드 할 사용자를위한 Excel 파일 만들기

<%@ page contentType="application/vnd.ms-excel" pageEncoding="ISO-8859-1"%> 
<%response.setHeader("Content-Disposition", "attachment;filename=myfile.xls"); %> 

과 비슷하지만 한 가지 중요한 예외가 있습니다. 사용자가 적절한 Excel 파일을 다운로드 할 수 있도록 허용해야합니다. 위의 코드는 클라이언트가 서버가 엑셀 파일을 보내고 있다고 간단히 말합니다.

답변

32

JSP 파일 대신 일반 서블릿에서 작업을 수행하십시오. JSP 파일은 동적으로 HTML 코드를 생성하기 위해 만들어졌으며 이진 출력 스트림 대신 문자 작성기를 사용하므로 본질적으로 이진 스트림 인 POI 생성 Excel 파일 만 손상시킬 수 있습니다.

그래서, 당신은 서블릿의 doGet() 방법으로 할 필요가 기본적으로 모든는 다음과 같습니다

이제
response.setContentType("application/vnd.ms-excel"); 
response.setHeader("Content-Disposition", "attachment; filename=filename.xls"); 
HSSFWorkbook workbook = new HSSFWorkbook(); 
// ... 
// Now populate workbook the usual way. 
// ... 
workbook.write(response.getOutputStream()); // Write workbook to response. 
workbook.close(); 

이 그것을 다운로드, 해당 URL 대신 JSP 파일이 서블릿을 호출합니다.

+0

writableworkbook의 경우는의 일부입니다 jexcel API가 맞습니까? 이것은 poi 권리를 사용하는 경우에도 작동해야합니다? – user571099

+0

@ user571099 통합 문서는 여기'HSSFWorkbook'이지,'WritableWorkbook'이 아닙니다. –

+0

이것은 정확히 내가 찾고 있었던 것이었다! Jersey RESTful 웹 서비스와 비슷하게 수행 할 수 있다고 가정합니다. – Brian

20

jsp가 아닌 서블릿을 사용하여 이진 첨부 파일을 작성하는 것이 더 일반적이지만 jsp에서 이진 첨부 파일을 작성할 수는 있습니다. 그렇게하는 것의 이점은 web.xml을 구성하거나 응용 프로그램을 다시로드 할 필요가 없다는 것입니다. 이는 웹 서버 환경에 따라 중요한 고려 사항이 될 수 있습니다.

poi를 사용하여 브라우저에 바이너리 첨부 파일을 보내는 예제 JSP입니다.

<%@page import="org.apache.poi.hssf.usermodel.*" %><%@page import="java.io.*" %><% 

// create a small spreadsheet 
HSSFWorkbook wb = new HSSFWorkbook(); 
HSSFSheet sheet = wb.createSheet(); 
HSSFRow row = sheet.createRow(0); 
HSSFCell cell = row.createCell(0); 
cell.setCellValue("Some text"); 

// write it as an excel attachment 
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); 
wb.write(outByteStream); 
byte [] outArray = outByteStream.toByteArray(); 
response.setContentType("application/ms-excel"); 
response.setContentLength(outArray.length); 
response.setHeader("Expires:", "0"); // eliminates browser caching 
response.setHeader("Content-Disposition", "attachment; filename=testxls.xls"); 
OutputStream outStream = response.getOutputStream(); 
outStream.write(outArray); 
outStream.flush(); 

%> 

중요한 트릭은 모든 수입과 코드를 시작하는 "<퍼센트"이전에 다른 지침을 한 줄이 있는지 확인하는 것입니다. 그렇지 않으면 jsp가 초기 새 행을 출력하여 출력을 손상시킬 수 있습니다.

또한 콘텐츠 길이를 항상 설정하는 것이 좋습니다. 일부 브라우저는 설정되지 않은 경우 제대로 작동하지 않습니다. 그래서 먼저 스프레드 시트를 바이트 배열로 출력하므로 실제로 데이터를 보내기 전에 길이를 설정할 수 있습니다. 당신이 돈을 다운로드하려면

+0

답변 해 주셔서 감사합니다.하지만 xls 파일의 경로를 어디에 정의해야합니까? 내 말은, jsp는 어떻게 알지? xls 파일을 어디에서 골라야할까요? 이전에 자바 프로그램에서 만든 pdf와 함께 사용할 수 있습니까? –

0

, t는 apche는 POI 사용이 느린 것입니다 통합 문서를 HSSF 사용하고 더 많은 공간을 소비 3.17 베타 1

SXSSFWorkbook workbook = new SXSSFWorkbook(100); 
workbook.setCompressTempFiles(true); 
Sheet sh = workbook.createSheet(); 
//write your data on sheet 

//below code will download file in browser default download folder 
response.setContentType("application/vnd.ms-excel"); 
      response.setHeader("Content-Disposition", "attachment; filename="+filename+".xlsx"); 
      workbook.write(response.getOutputStream()); 
      workbook.close(); 
      workbook.dispose(); 

의 PDF를 사용하여 itext

 Document document = new Document(); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
      PdfWriter.getInstance(document, baos); 
      document.open(); 
//write your code 

document.add("content"); 
      document.close(); 
      response.setHeader("Expires", "0"); 
      response.setHeader("Cache-Control","must-revalidate, post-check=0, pre-check=0"); 
      response.setHeader("Pragma", "public"); 
      response.setContentType("application/pdf"); 
      response.addHeader("Content-Disposition", "attachment; filename="+filename+".pdf"); 
      response.setContentLength(baos.size()); 
      OutputStream os = response.getOutputStream(); 
      baos.writeTo(os); 
      os.flush(); 
      os.close();