문제

웹 애플리케이션 사용자가 일부 데이터를 Excel 파일로 다운로드하기를 원합니다.

응답 객체에서 입력 스트림을 보낼 다음 기능이 있습니다.

public static void sendFile(InputStream is, HttpServletResponse response) throws IOException {
        BufferedInputStream in = null;
        try {
            int count;
            byte[] buffer = new byte[BUFFER_SIZE];
            in = new BufferedInputStream(is);
            ServletOutputStream out = response.getOutputStream();
            while(-1 != (count = in.read(buffer)))
                out.write(buffer, 0, count);
            out.flush();            
        }   catch (IOException ioe) { 
            System.err.println("IOException in Download::sendFile"); 
            ioe.printStackTrace();
        } finally {
            if (in != null) {
                try { in.close(); 
                } catch (IOException ioe) { ioe.printStackTrace(); }
            }   
        }
    }

hssfworkbook 객체를 입력 스트림으로 변환하고 이전 방법으로 전달하고 싶습니다.

public InputStream generateApplicationsExcel() {
    HSSFWorkbook wb = new HSSFWorkbook();
    // Populate the excel object
    return null; // TODO. return the wb as InputStream 
}

http://poi.apache.org/apidocs/org/apache/poi/hssf/usermodel/hssfworkbook.html

도움이 되었습니까?

해결책

질문의 문제는 출력 스트림과 입력 스트림을 혼합하고 있다는 것입니다. 입력 스트림은 당신이 읽은 내용이며 출력 스트림은 당신이 쓰는 것입니다.

이것이 출력 스트림에 POI 객체를 작성하는 방법입니다.

// this part is important to let the browser know what you're sending
response.setContentType("application/vnd.ms-excel");
// the next two lines make the report a downloadable file;
// leave this out if you want IE to show the file in the browser window
String fileName = "Blah_Report.xls";
response.setHeader("Content-Disposition", "attachment; filename=" + fileName); 

// get the workbook from wherever
HSSFWorkbook wb = getWorkbook();
OutputStream out = response.getOutputStream();
try {
   wb.write(out);
}       
catch (IOException ioe) { 
  // if this happens there is probably no way to report the error to the user
  if (!response.isCommited()) {
    response.setContentType("text/html");
    // show response text now
  }
}

기존 코드를 재사용하려면 POI 데이터를 어딘가에 저장해야합니다.이를 입력 스트림으로 바꾸십시오. BytearRayoutputStream에 작성한 다음 BytearRayInputStream을 사용하여 바이트를 읽음으로써 쉽게 수행 할 수 있지만 권장하지는 않습니다. 기존 방법은 입력 스트림에서 및 출력 스트림으로 데이터를 파이프 할 수있는 일반 파이프 구현으로 더 유용하지만 POI 객체를 작성할 필요는 없습니다.

다른 팁

객체에서 입력 스트림을 만들 수 있습니다.

public InputStream generateApplicationsExcel() {
    HSSFWorkbook wb = new HSSFWorkbook();
    // Populate a InputStream from the excel object
    return new ByteArrayInputStream(excelFile.getBytes());
}

나는 당신이 무엇을하려고하는지 이해한다고 생각합니다 (어쩌면 나는 어쩌면 으르렁 거리는 일입니다)

실제로 많은 코드가 필요하지 않습니다. 쓰기 방법을 확인하십시오.

HSSFWorkbook wb = new HSSFWorkBook();
//populate

ServletOutputStream out = response.getOutputStream();
try {
   wb.write(out);
   out.flush();
}       
catch (IOException ioe) { 
   //whatever
}
out.close();

내가 POI와 함께 일했을 때를 기억하는 한, 그것이 내가 한 일입니다. 웹 프레임 워크 안에 있다면 프레임 워크가 닫은 후에 그 servletoutputstream으로 무언가를 시도하지 않도록 그것을 지울 수 있습니다. 시도하면 출력 스트림이 이미 닫혔다는 사실을 알리는 예외를 얻을 수 있습니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top