1. 소개
보고서는 종종 Java 웹 개발에 관여합니다. 최근 프로젝트에서는 데이터베이스의 데이터를 테이블로 표시하고 Excel 파일로 내보내야합니다.
2. 관련 항아리 패키지
POI를 사용하면 Excel 가져 오기 및 수출 문제를 잘 해결할 수 있습니다. POI 다운로드 주소 :
POI-3.6-20091214.jar
3. 키 코드
먼저 위의 JAR 패키지를 가져옵니다.
Excel을 생성 할 때 일반 데이터 소스 양식이 목록입니다. 다음은 Excel 형식을 생성하는 코드입니다.
/ *** 다음은 Excel Operation 생성입니다* // 1. Excel 파일에 해당하는 통합 문서 작성 WB = New Hssfworkbook (); // 2. Excel의 시트에 해당하는 통합 문서에 시트를 추가합니다. // 3. 시트에 테이블 헤더의 0 줄을 추가합니다. 이전 버전 POI는 Excel 행의 수에 제한이 있습니다. 짧은 hssfrow row = sheet.createrow ((int) 0); // 4. 셀을 만들고 값 테이블 헤더를 설정 한 다음 테이블 헤더를 중앙으로 설정합니다. // centering format style.setalignment (hssfcellstyle.align_center); // 테이블 헤더 설정 hssfcell cell = row.createcell (0); Cell.setCellValue ( "Table Header1"); Cell.setCellStyle (스타일); cell = row.createcell (1); cell.setCellValue ( "Table Header2"); Cell.setCellStyle (스타일); cell = row.createcell (2); cell.setCellValue ( "Table Header3"); Cell.setCellStyle (스타일); cell = row.createcell (3); cell.setCellValue ( "테이블 헤더 4"); Cell.setCellStyle (스타일); cell = row.createcell (4); cell.setCellValue ( "테이블 헤더 5"); Cell.setCellStyle (스타일);
Excel 형식을 생성 한 후에는 Excel에 데이터를 작성해야합니다.
// (int i = 0; i <lists.size (); i ++) {row = sheet.createrow ((int) i+1); 목록 = lists.get (i); // 셀을 생성하고 값을 설정합니다. row.createCell (1) .setCellValue (list.getxxx ()); row.createCell (2) .setCellValue (list.getxxx ()); row.createcell (3) .setCellValue (list.getxxx ()); row.createcell (3) .setCellValue (list.getxxx ()); row.createCell (4) .setCellValue (list.getxxx ()); } 결과 Excel은 스트림으로 출력됩니다.
*다운로드 상자가 나타나지 않습니다
fileoutputStream out = 새 FileOutputStream ( "e : /xxx.xls"); wb.write (out); out.close ();
*다운로드 상자를 팝업하십시오
문자열 filename = "xxx 테이블"; bytearrayoutputStream os = 새로운 BytearRayoutputStream (); WB.WRITE (OS); 바이트 [] content = os.tobytearray (); inputStream은 = New ByTearRayInputStream (Content); // 다운로드 페이지를 열도록 응답 매개 변수를 설정합니다. res.reset (); res.setContentType ( "application/vnd.ms-excel; charset = utf-8"); res.setheader ( "content-disposition", "attachment; filename =" + new String ((filename + ".xls"). getBytes (), "iso-8859-1"); servletoutputStream out = res.getOutputStream (); bufferedInputStream bis = null; BufferedOutputStream BOS = NULL; try {bis = new bufferedInputStream (IS); BOS = 새로운 BufferedOutputStream (out); 바이트 [] buff = 새로운 바이트 [2048]; int bytesread; // 간단한 읽기/쓰기 루프. while (-1! = (bytesread = bis.read (buff, 0, buff.length))) {bos.write (buff, 0, bytesread); }} catch (예외 e) {// todo : 핸들 예외 e.printstacktrace (); } 마침내 {if (bis! = null) bis.close (); if (bos! = null) bos.close (); } 위의 작업을 완료 한 후 다른 페이지로 이동할 수 있습니다.
동시에 POI는 웹 페이지에 Excel 업로드 및 구문 분석을 표시 할 수도 있습니다. 이 다른 기사 요약을 계속 지켜봐 주시기 바랍니다!
위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.