Java 는 poi 구성 요소 로 Excel 형식 데 이 터 를 내 보 냅 니 다.

관리 시스템 을 할 때 엑셀 의 도 출 은 우리 가 피하 기 어렵 고 실 용적 이 고 인성 화 된 기능 이 라 고 생각 합 니 다.
자바 에 서 는 엑셀 에 대한 지원 이 JXL,POI 등 여러 가지 가 있다.제 가 사용 하 는 것 은 POI 에서 엑셀 작업 을 하 는 것 입 니 다.다음은 POI 구성 요소 의 사용 과 제 가 사용 하 는 도구 류 를 간단하게 공유 하 겠 습 니 다.
POI 구성 요소
poi 구성 요 소 는 아파 치가 제공 하 는 구성 요소 패키지 입 니 다.주요 직책 은 자바 프로그램 에 office 문서 에 대한 작업 을 제공 하 는 것 입 니 다.본 고 는 주로 엑셀 조작 에 대한 소개 이다.
공식 홈 페이지:http://poi.apache.org/index.html
API 문서:http://poi.apache.org/apidocs/index.html
POI 구성 요소 기본 소개
사용 할 때 우 리 는 poi 구성 요소 가 우리 에 게 제공 하 는 엑셀 작업 과 관련 된 종 류 는 모두 HSSF 로 시작 하 는 것 을 발견 할 수 있 습 니 다.이런 종 류 는 주로 org.apache.pai.hssf.usermodel 이 가방 아래 에 있 습 니 다.엑셀 과 같은 대상,셀 의 스타일,글꼴 스타일 과 부분의 도구 류 가 포함 되 어 있 습 니 다.우리 가 자주 사용 하 는 몇 가지 종 류 를 소개 합 니 다.
  • HSSFWorkbook:Excel 대상 은.xls/.xlsx 파일 에 해당 합 니 다
  • HSSFSheet:워 크 시트 대상,Excel 파일 에 포 함 된 sheet,한 대상 은 하나의 폼 을 대표 합 니 다
  • HSSFRow:표 의 줄 대상 을 나타 낸다
  • HSSFCell:표 의 셀 대상 을 표시 합 니 다
  • HSSFHeader:Excel 문서 Sheet 의 머 릿 말..
  • HSSFFooter:Excel 문서 Sheet 의 꼬 릿 말..
  • HSSFDataFormat:날짜 형식..
  • HSSFFont:글꼴 대상.
  • HSSFCellStyle:셀 스타일(스타일,테두리 등 정렬)
  • HSSFComment:주석(주석)
  • HSSFPatriarch:HSSFComment 과 주석 을 만 드 는 위치 입 니 다
  • HSSFColor:색상 대상.HSSFDateUtil:날짜 보조 도구HSSFPrintSetup:인쇄 보조 도구
  • HSSFErrorConstants:오류 정보 표
  • POI 모듈 기본 동작
    1.HSSFWorkbook'Excel 파일 대상'만 들 기
    
    //  Excel  
    HSSFWorkbook workbook = new HSSFWorkbook();
    2.워 크 북 대상 을 사용 하여 워 크 시트 대상 만 들 기
    
    //      
    HSSFSheet sheet = workbook.createSheet("    "); 
    3.줄 과 작업 셀 대상 만 들 기
    
    //  HSSFRow   ( )
    HSSFRow row = sheet.createRow(0); 
    
    //  HSSFCell   (   )
    HSSFCell cell=row.createCell(0); 
    
    //        
    cell.setCellValue("       "); 
    4.Excel 파일 저장
    
    //  Excel   
    FileOutputStream output=new FileOutputStream("d:\\workbook.xls"); 
    
    workbook.write(output); 
    
    output.flush(); 
    맞 춤 형 내 보 내기 스타일 설정
    여기 제 가 자주 사용 하 는 스타일 설정 방법 을 열거 하 겠 습 니 다!
    1.셀 을 합 쳐 너비,높이 설정
    
    //        
    HSSFCellStyle cellStyle = workbook.createCellStyle(); 
    //     
    cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); 
    //     
    cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
    //     ---    
    cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS); 
    //       (           )
    cellStyle.setFillForegroundColor(HSSFColor.RED.index); 
    //        
    cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index); 
    //     
    cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT); 
    //     
    cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index); 
    //        
    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  
    
    //         
    cell.setCellStyle(cellStyle); 
    //        
    row.setRowStyle(cellStyle);
    2.셀 스타일 설정
    
    //        
    HSSFCellStyle cellStyle = workbook.createCellStyle(); 
    //     
    cellStyle.setAlignment(HSSFCellStyle.ALIGN_JUSTIFY); 
    //     
    cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);  
    //     ---    
    cellStyle.setFillPattern(HSSFCellStyle.DIAMONDS); 
    //       (           )
    cellStyle.setFillForegroundColor(HSSFColor.RED.index); 
    //        
    cellStyle.setFillBackgroundColor(HSSFColor.LIGHT_YELLOW.index); 
    //     
    cellStyle.setBorderBottom(HSSFCellStyle.BORDER_SLANTED_DASH_DOT); 
    //     
    cellStyle.setBottomBorderColor(HSSFColor.DARK_RED.index); 
    //        
    cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));  
    
    //         
    cell.setCellStyle(cellStyle); 
    //        
    row.setRowStyle(cellStyle);
    3.글꼴 설정
    
    //        
    HSSFFont fontStyle = workbook.createFont(); 
    //   
    fontStyle.setFontName("  ");  
    //    
    fontStyle.setFontHeightInPoints((short)12);  
    //    
    font.setColor(HSSFColor.BLUE.index); 
    //    
    fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
    //     
    font.setItalic(true); 
    //     
    font.setUnderline(HSSFFont.U_SINGLE); 
    //             
    cellStyle.setFont(font);
    개인 용도
    다음은 개인의 전체적인 사용 과정 을 공유 하 겠 습 니 다!

    처리 액 션
    
        //         
        List<PBillBean> dataset = new ArrayList<PBillBean>();
        //  dataset
        for (int i = 0; i < 10; i++) {
          PBillBean bean = new PBillBean();
          dataset.add(bean);
        }
        //    
        File tempFile = null;
        try {
          //Excel     
          ExportExcel<PBillBean> ex = new ExportExcel<PBillBean>();
          //      
          String[] headers = { "  1", "  2", "  3", "  4",  "  5", "  6" };
          //     
          SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
          //       
          String filename = "bill_" + format.format(new Date()) + ".xls";
          //       
          String rootDir = request.getSession().getServletContext().getRealPath("/");
          //        
          String path = rootDir + File.separator + "tempfile";
          File saveDir = new File(path);
          if (!saveDir.exists()) {
            saveDir.mkdirs();//              
          }
          //    
          path = path + File.separator + filename;
          tempFile = new File(path);  //       
          //   
          OutputStream out = new FileOutputStream(tempFile);
          //   Excel  
          HSSFWorkbook workbook = new HSSFWorkbook();
          //      
          String[] sheetNames = { "    " };
          for (int i = 0; i < sheetNames.length; i++) {
            workbook.createSheet(sheetNames[i]);
          }
          //   Excel
          ex.exportExcel(sheetNames[0], headers, dataset, out,
              "yyyy-MM-dd HH:mm", workbook);
          try {
            //    
            workbook.write(out);
          } catch (IOException e) {
            e.printStackTrace();
          }
          out.close();
          //          。
          BufferedInputStream fis = new BufferedInputStream(
              new FileInputStream(path));
          byte[] buffer = new byte[fis.available()];
          fis.read(buffer);
          fis.close();
          //   response
          response.reset();
          //   response Header
          response.addHeader("Content-Disposition", "attachment;filename="
              + new String(filename.getBytes()));
          response.addHeader("Content-Length", "" + tempFile.length());
          OutputStream toClient = new BufferedOutputStream(
              response.getOutputStream());
          response.setContentType("application/vnd.ms-excel;charset=utf-8");
          toClient.write(buffer);
          toClient.flush();
          toClient.close();
        } catch (Exception e) {
          e.printStackTrace();
        } finally {
          if (tempFile != null && tempFile.exists()) {
            tempFile.delete();//       
          }
        }
    Excel 도구 클래스 내 보 내기
    
    public void exportExcel(String title, String[] headers, Collection<T> dataset, OutputStream out, String pattern,HSSFWorkbook workbook) 
      { 
        //                 
        HSSFSheet sheet = workbook.getSheet(title);
        //           15    
        sheet.setDefaultColumnWidth((short) 15); 
        //        
        HSSFCellStyle style = workbook.createCellStyle(); 
        //        
        style.setFillForegroundColor(HSSFColor.SKY_BLUE.index); 
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
        style.setBorderRight(HSSFCellStyle.BORDER_THIN); 
        style.setBorderTop(HSSFCellStyle.BORDER_THIN); 
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
        //        
        HSSFFont font = workbook.createFont(); 
        font.setColor(HSSFColor.VIOLET.index); 
        font.setFontHeightInPoints((short) 12); 
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); 
        //             
        style.setFont(font); 
        //            
        HSSFCellStyle style2 = workbook.createCellStyle(); 
        style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index); 
        style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
        style2.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
        style2.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
        style2.setBorderRight(HSSFCellStyle.BORDER_THIN); 
        style2.setBorderTop(HSSFCellStyle.BORDER_THIN); 
        style2.setAlignment(HSSFCellStyle.ALIGN_CENTER); 
        style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); 
        //         
        HSSFFont font2 = workbook.createFont(); 
        font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL); 
        //             
        style2.setFont(font2); 
        //              
        HSSFPatriarch patriarch = sheet.createDrawingPatriarch(); 
        //           ,     
        HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5)); 
        //        
        comment.setString(new HSSFRichTextString("   POI     !")); 
        //       ,                       . 
        comment.setAuthor("leno"); 
    
        //         
        HSSFRow row = sheet.createRow(0); 
        for (short i = 0; i < headers.length; i++) 
        { 
          HSSFCell cell = row.createCell(i); 
          cell.setCellStyle(style); 
          HSSFRichTextString text = new HSSFRichTextString(headers[i]); 
          cell.setCellValue(text); 
        } 
        //       ,      
        Iterator<T> it = dataset.iterator(); 
        int index = 0; 
        while (it.hasNext()) 
        { 
          index++; 
          row = sheet.createRow(index); 
          T t = (T) it.next(); 
          //     ,  javabean       ,    getXxx()        
          Field[] fields = t.getClass().getDeclaredFields(); 
          for (short i = 0; i < fields.length; i++) 
          { 
            HSSFCell cell = row.createCell(i); 
            cell.setCellStyle(style2); 
            Field field = fields[i]; 
            String fieldName = field.getName(); 
            String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 
            try 
            { 
              Class tCls = t.getClass(); 
              Method getMethod = tCls.getMethod(getMethodName, new Class[] {}); 
              Object value = getMethod.invoke(t, new Object[] {}); 
              //                 
              String textValue = null; 
              if (value instanceof Boolean) 
              { 
                boolean bValue = (Boolean) value; 
                textValue = " "; 
                if (!bValue) 
                { 
                  textValue = " "; 
                } 
              } 
              else if (value instanceof Date) 
              { 
                Date date = (Date) value; 
                SimpleDateFormat sdf = new SimpleDateFormat(pattern); 
                textValue = sdf.format(date); 
              } 
              else if (value instanceof byte[]) 
              { 
                //     ,     60px; 
                row.setHeightInPoints(60); 
                //           80px,            
                sheet.setColumnWidth(i, (short) (35.7 * 80)); 
                // sheet.autoSizeColumn(i); 
                byte[] bsValue = (byte[]) value; 
                HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,1023, 255, (short) 6, index, (short) 6, index); 
                anchor.setAnchorType(2); 
                patriarch.createPicture(anchor, workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG)); 
              } 
              else 
              { 
                //                  
                textValue = value == null? "": value.toString(); 
              } 
              //         ,          textValue          
              if (textValue != null) 
              { 
                Pattern p = Pattern.compile("^//d+(//.//d+)?$"); 
                Matcher matcher = p.matcher(textValue); 
                if (matcher.matches()) 
                { 
                  //      double   
                  cell.setCellValue(Double.parseDouble(textValue)); 
                } 
                else 
                { 
                  HSSFRichTextString richString = new HSSFRichTextString(textValue); 
                  HSSFFont font3 = workbook.createFont(); 
                  font3.setColor(HSSFColor.BLUE.index); 
                  richString.applyFont(font3); 
                  cell.setCellValue(richString); 
                } 
              } 
            } 
            catch (SecurityException e) 
            { 
              e.printStackTrace(); 
            } 
            catch (NoSuchMethodException e) 
            { 
              e.printStackTrace(); 
            } 
            catch (IllegalArgumentException e) 
            { 
              e.printStackTrace(); 
            } 
            catch (IllegalAccessException e) 
            { 
              e.printStackTrace(); 
            } 
            catch (InvocationTargetException e) 
            { 
              e.printStackTrace(); 
            } 
            finally 
            { 
              //      
            } 
          } 
        } 
      }
    작은 매듭
    Excel 데이터 의 내 보 내기 가 큰 성 과 를 거 두 었 습 니 다.개인 적 으로 이 내 보 내기 도구 류 가 좋 은 것 같 습 니 다.여러분 들 이 좋아 하 시 기 를 바 랍 니 다!
    자바 에서 poi 구성 요 소 를 사용 하여 Excel 형식 데 이 터 를 내 보 내 는 것 에 대한 더 많은 글 은 아래 링크 를 보십시오.

    좋은 웹페이지 즐겨찾기