자바 사용 poi 동적 내 보 내기 동작

11859 단어 자바poi도 출
사용자 가 원 하 는 필드 의 데 이 터 를 실현 하면 그 필드 의 데 이 터 를 내 보 냅 니 다.저 는\#분할 필드 를 사용 하여 이 루어 집 니 다.
필드 값 을 입력 할 때 글 을 씁 니 다.
엑셀 내 보 내기 도구 클래스 를 만 듭 니 다.

package com.zy.util;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Font;
/**
 * * 
 * 
 * @Title: ExportExcelUtil.java 
 * @Package com.jarmsystem.web.util    :   POI javaee  Excel    
 * @author    
 * @date 2018 11 16    10:38:00
 * @version V1.0 
 */
public class ExPortExcelUtil {
	/**
	 * 
	 * @param response
	 *     
	 * @param fileName
	 *        :"   "
	 * @param excelHeader
	 *   excel    ,  "   #admin"     ,"   " excel   , "admin"      
	 * @param dataLis
	 *       ,             ,    javabean  (     )
	 * @return     HSSFWorkbook
	 * @throws Exception
	 */
	public static <T> HSSFWorkbook export(HttpServletResponse response, String fileName, String[] excelHeader,
			Collection<T> dataLis) throws Exception {
		response.setContentType("application/x-download");
		response.setCharacterEncoding("utf-8");//       
		response.setHeader("Content-Disposition",
				"attachment;filename=" + new String(fileName.getBytes("gbk"), "iso8859-1") + ".xls");//       
		//        
		HSSFWorkbook wb = new HSSFWorkbook();
		//       
		HSSFCellStyle titleStyle = wb.createCellStyle();
		//           
		titleStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);//         
		titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);//         
		titleStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);//         
		titleStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);//        
		//           
		titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//      
		titleStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//      
		//        
		Font titleFont = wb.createFont();
		titleFont.setFontHeightInPoints((short) 15);//      
		titleFont.setFontName("  ");//      
		titleStyle.setFont(titleFont);
		//   workBook         sheet(   )   excel    sheet
		HSSFSheet sheet = wb.createSheet();
		//     
		String[] titleArray = new String[excelHeader.length];
		//      
		String[] fieldArray = new String[excelHeader.length];
		for (int i = 0; i < excelHeader.length; i++) {
			String[] tempArray = excelHeader[i].split("#");
			titleArray[i] = tempArray[0];
			fieldArray[i] = tempArray[1];
		}
		//  sheet      
		HSSFRow row = sheet.createRow(0);//    0  
		//       
		sheet.autoSizeColumn(0);
		//          
		sheet.setDefaultColumnWidth(20);
		//       
		for (int i = 0; i < titleArray.length; i++) {
			//        +1   0       
			HSSFCell titleCell = row.createCell(i);
			titleCell.setCellValue(titleArray[i]);
			titleCell.setCellStyle(titleStyle);
			sheet.autoSizeColumn(i + 1); // 0       
		}
		//                     ,     
		HSSFCellStyle dataStyle = wb.createCellStyle();
		//       
		dataStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
		dataStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
		dataStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
		dataStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
		//        
		dataStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//      
		dataStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//      
		//        
		Font dataFont = wb.createFont();
		dataFont.setFontHeightInPoints((short) 12);//      
		dataFont.setFontName("  ");//    
		dataStyle.setFont(dataFont);
		//      ,     
		Iterator<T> it = dataLis.iterator();
		int index = 0;
		while (it.hasNext()) {
			index++; //    0     
			row = sheet.createRow(index);
			T t = it.next();
			//                 ,       getxxx()       
			for (int i = 0; i < fieldArray.length; i++) {
				//          i+1
				HSSFCell dataCell = row.createCell(i);
				dataCell.setCellStyle(dataStyle);
				sheet.autoSizeColumn(i);
				String fieldName = fieldArray[i];
				//      getxxx()                    
				String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
				Class<? extends Object> tCls = t.getClass();//    Object    Object   
				Method getMethod = tCls.getMethod(getMethodName, new Class[] {});//             
				Object value = getMethod.invoke(t, new Object[] {});//       ,     
				if (value != null) {
					dataCell.setCellValue(value.toString());//       
				}
			}
		}
		OutputStream outputStream = response.getOutputStream();//     
		wb.write(outputStream);// HSSFWorkbook    
		wb.close();// HSSFWorkbook   
		outputStream.flush();//     
		outputStream.close();//     
		
		// excel     
		// XSSFCellStyle.ALIGN_CENTER      
		// XSSFCellStyle.ALIGN_LEFT     
		// XSSFCellStyle.ALIGN_RIGHT     
		// XSSFCellStyle.VERTICAL_TOP     
		// XSSFCellStyle.VERTICAL_CENTER     
		// XSSFCellStyle.VERTICAL_BOTTOM     
		// CellStyle.BORDER_DOUBLE     
		// CellStyle.BORDER_THIN     
		// CellStyle.BORDER_MEDIUM      
		// CellStyle.BORDER_DASHED      
		// CellStyle.BORDER_HAIR         
		// CellStyle.BORDER_THICK     
		return wb;
	}
}
controller 계층 호출

/**
	 *      excel (               )
	 * 
	 * @param request
	 * @param response
	 * @param expor
	 * @throws Exception
	 */
	@RequestMapping("/excelOut")
	public void ExcelOut(HttpServletRequest request, HttpServletResponse response, String export) {
		export = "   #admin,id#id"; // ,    #adminPhone        
		String[] excelHeader = export.split(",");
		List<Tb_User> projectList = new ArrayList<Tb_User>();
		Tb_User tb_User = new Tb_User();
  //                
		tb_User.setAdmin("   ");
		tb_User.setId("1111");
		tb_User.setAdminPhone("111");
		projectList.add(tb_User);
		try {
			ExPortExcelUtil.export(response, "   ", excelHeader, projectList);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("    !");
		}
	}
세 필드 의 실체 클래스 에서 필요 한 두 필드 데 이 터 를 내 보 냅 니 다.

추가 지식:자바 는 poi 를 사용 하여 엑셀 의 내용 을 내 보 내 는 동시에 반 사 를 이용 하여 동적 으로 정 보 를 얻 을 수 있 습 니 다.
자바-pi 내 보 내기
우 리 는 많은 사람들 이 우리 가 자바 내 보 낼 도구 류 를 쓸 수 있 기 를 바 랍 니 다.플러그 인 으로 실현 할 필요 가 없습니다.다음은 제 가 쓴 자바 내 보 내기 도구 류 입 니 다.더 이상 말 하지 않 고 시작 합 니 다.
우선,우 리 는 maven 프로젝트 를 대상 으로 해당 하 는 의존 도 를 가 져 옵 니 다.

<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi</artifactId>
  <version>3.14</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.14</version>
</dependency>
해당 의존 도 를 가 져 온 후에 우 리 는 해당 코드 를 작성 할 수 있 습 니 다.다음은 제 가 작성 한 코드 입 니 다.여기 서 우리 가 들 어 온 것 은 일반적인 클래스 입 니 다.

public void getexport(Collection< T> dataset ,String[] headers , HttpServletResponse response , HttpServletRequest request ,String fileName){
  //    excel  ,excel    
  HSSFWorkbook workbook= new HSSFWorkbook() ;
  //    excel  
  HSSFSheet sheet= workbook.createSheet(fileName) ;
  //       1
  HSSFCellStyle cellStyle1=workbook.createCellStyle() ;
  //       
  cellStyle1.setAlignment(HSSFCellStyle. ALIGN_CENTER) ;
  //     
  cellStyle1.setFillPattern(HSSFCellStyle. SOLID_FOREGROUND) ;
  cellStyle1.setFillForegroundColor(HSSFColor.YELLOW. index) ;
  //    
  cellStyle1.setBorderLeft(HSSFCellStyle. BORDER_THIN) ;
  cellStyle1.setBorderRight(HSSFCellStyle. BORDER_THIN) ;
  cellStyle1.setBorderTop(HSSFCellStyle. BORDER_THIN) ;
  cellStyle1.setBorderBottom(HSSFCellStyle. BORDER_THIN) ;
  //       2
  HSSFCellStyle cellStyle2=workbook.createCellStyle() ;
  //       
  cellStyle2.setAlignment(HSSFCellStyle. ALIGN_CENTER) ;
  //    
  cellStyle2.setBorderLeft(HSSFCellStyle. BORDER_THIN) ;
  cellStyle2.setBorderRight(HSSFCellStyle. BORDER_THIN) ;
  cellStyle2.setBorderTop(HSSFCellStyle. BORDER_THIN) ;
  cellStyle2.setBorderBottom(HSSFCellStyle. BORDER_THIN) ;
  //     ,    
  HSSFRow row= sheet.createRow( 0) ;
  for( int i= 0 ;i<headers. length ;i++){
    HSSFCell cell=row.createCell(i) ;
    cell.setCellStyle(cellStyle1) ;
    cell.setCellValue(headers[i]) ;
  }
  //        
  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 ( int i= 0 ;i<fields. length ;i++){
      HSSFCell cell= row.createCell(i) ;
      cell.setCellStyle(cellStyle2) ;
      Object value=getFildValue(fields[i] ,t) ;
      //                
      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( "yyyy-MM-dd") ;
        textValue = sdf.format(date) ;
      } else
      {
        //                 
        textValue = value.toString() ;
      }
      if (textValue!= null){
          cell.setCellValue(textValue) ;
      }
    }
  }
  //  excel  
  OutputStream output= null;
  try {
    output=response.getOutputStream() ;
    response.setHeader( "Content-disposition" , "attachment; filename="+ URLEncoder. encode(fileName , "UTF-8")+ ".xls") ;
    response.setContentType( "application/vnd.ms-excel;charset=UTF-8") ;
    workbook.write(output) ;
  } catch (IOException e) {
    e.printStackTrace() ;
  } finally {
    try {
      output.close() ;
    } catch (IOException e) {
      e.printStackTrace() ;
    }
  }
}
다음 절 에 나 는 앞으로 우리 의 도구 류 를 jar 가방 으로 만 드 는 방법 을 실현 할 것 이다.그러면 우 리 는 우리 의 jar 가방 을 우리 의 프로젝트 에 가 져 올 수 있다.
이상 의 자바 에서 poi 를 사용 하여 동적 으로 내 보 내 는 작업 은 바로 편집장 이 여러분 에 게 공유 한 모든 내용 입 니 다.여러분 께 참고 가 되 고 여러분 들 이 저 희 를 많이 사랑 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기