공공 POI 내 보 내기 Excel 방법 상세 설명

9948 단어 자바POI도 출Excel
처음에 데이터 엑셀 내 보 내기 기능 을 했 지만 나중에 내 보 낼 때마다 비슷 한 코드 를 많이 써 야 하기 때문에 공공 내 보 내기 방법 을 조금 연구 했다.
POI 를 사용 한 다음 에 하나의 공공 클래스 로 써 서 형식 이 설 정 된 데 이 터 를 입력 하면 다운로드 상 자 를 팝 업 할 수 있 습 니 다.
(getResponse 방법 을 보충 합 니 다.이전 에는 계승 이 있 는 지 주의 하지 않 았 습 니 다!)

package com.hwt.glmf.common;
 
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
 
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.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.hssf.util.CellRangeAddress;
import org.apache.poi.hssf.util.HSSFColor;
 
/**
 *   Excel    
 * @version 1.0
 * 
 * @author wangcp
 *
 */
public class ExportExcel extends ActionSupport implements ServletRequestAware{
	
	//         
	private String title;
	//      
	private String[] rowName ;
	
	private List<Object[]> dataList = new ArrayList<Object[]>();
	
	HttpServletResponse response;
	
	//    ,        
	public ExportExcel(String title,String[] rowName,List<Object[]> dataList){
		this.dataList = dataList;
		this.rowName = rowName;
		this.title = title;
	}
			
	/*
	 *     
	 * */
	public void export() throws Exception{
		try{
			HSSFWorkbook workbook = new HSSFWorkbook();						//        
			HSSFSheet sheet = workbook.createSheet(title);		 			//      
			
			//        
	 HSSFRow rowm = sheet.createRow(0);
	 HSSFCell cellTiltle = rowm.createCell(0);
	 
	 //sheet    【getColumnTopStyle()/getStyle()        -     -    】
	 HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//        
	 HSSFCellStyle style = this.getStyle(workbook);					//       
	 
	 sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1))); 
	 cellTiltle.setCellStyle(columnTopStyle);
	 cellTiltle.setCellValue(title);
 		
			//       
			int columnNum = rowName.length;
			HSSFRow rowRowName = sheet.createRow(2);				//    2      (           )
			
			//       sheet     
			for(int n=0;n<columnNum;n++){
				HSSFCell cellRowName = rowRowName.createCell(n);				//            
				cellRowName.setCellType(HSSFCell.CELL_TYPE_STRING);				//            
 			HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
 			cellRowName.setCellValue(text);									//         
 			cellRowName.setCellStyle(columnTopStyle);						//         
 		}
			
 		//          sheet       
			for(int i=0;i<dataList.size();i++){
				
				Object[] obj = dataList.get(i);//      
				HSSFRow row = sheet.createRow(i+3);//       
				
				for(int j=0; j<obj.length; j++){
					HSSFCell cell = null; //          
					if(j == 0){
						cell = row.createCell(j,HSSFCell.CELL_TYPE_NUMERIC);
						cell.setCellValue(i+1);	
					}else{
						cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);
						if(!"".equals(obj[j]) && obj[j] != null){
							cell.setCellValue(obj[j].toString());						//       
						}
					}
					cell.setCellStyle(style);									//       
				}
			}
			//              
			for (int colNum = 0; colNum < columnNum; colNum++) {
	  int columnWidth = sheet.getColumnWidth(colNum) / 256;
	  for (int rowNum = 0; rowNum < sheet.getLastRowNum(); rowNum++) {
	  HSSFRow currentRow;
	  //        
	  if (sheet.getRow(rowNum) == null) {
	   currentRow = sheet.createRow(rowNum);
	  } else {
	   currentRow = sheet.getRow(rowNum);
	  }
	  if (currentRow.getCell(colNum) != null) {
	   HSSFCell currentCell = currentRow.getCell(colNum);
	   if (currentCell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
	   int length = currentCell.getStringCellValue().getBytes().length;
	   if (columnWidth < length) {
	    columnWidth = length;
	   }
	   }
	  }
	  }
	  if(colNum == 0){
	  	sheet.setColumnWidth(colNum, (columnWidth-2) * 256);
	  }else{
	  	sheet.setColumnWidth(colNum, (columnWidth+4) * 256);
	  }
	 }
			
			if(workbook !=null){
				try
			 {
			 String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
			 String headStr = "attachment; filename=\"" + fileName + "\"";
			 response = getResponse();
			 response.setContentType("APPLICATION/OCTET-STREAM");
			 response.setHeader("Content-Disposition", headStr);
			 OutputStream out = response.getOutputStream();
			 workbook.write(out);
			 }
			 catch (IOException e)
			 {
			 e.printStackTrace();
			 }
			}
 
		}catch(Exception e){
			e.printStackTrace();
		}
		
	}
 
 /**
 *   response
 **/
 private HttpServletResponse getResponse(){
 HttpServletResponse response = ServletActionContext.getResponse();
		return response;
 }
	
	/* 
	 *        
	 */ 
 	public HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
 		
 		 //     
 	 HSSFFont font = workbook.createFont();
 	 //      
 	 font.setFontHeightInPoints((short)11);
 	 //    
 	 font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 	 //       
 	 font.setFontName("Courier New");
 	 //    ; 
 	 HSSFCellStyle style = workbook.createCellStyle();
 	 //     ; 
 	 style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 	 //       ; 
 	 style.setBottomBorderColor(HSSFColor.BLACK.index);
 	 //     ; 
 	 style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 	 //       ; 
 	 style.setLeftBorderColor(HSSFColor.BLACK.index);
 	 //     ; 
 	 style.setBorderRight(HSSFCellStyle.BORDER_THIN);
 	 //       ; 
 	 style.setRightBorderColor(HSSFColor.BLACK.index);
 	 //     ; 
 	 style.setBorderTop(HSSFCellStyle.BORDER_THIN);
 	 //       ; 
 	 style.setTopBorderColor(HSSFColor.BLACK.index);
 	 //           ; 
 	 style.setFont(font);
 	 //      ; 
 	 style.setWrapText(false);
 	 //              ; 
 	 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
 	 //              ; 
 	 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
 	 
 	 return style;
 	 
 	}
 	
 	/* 
	 *           
	 */ 
 	public HSSFCellStyle getStyle(HSSFWorkbook workbook) {
	 	 //     
	 	 HSSFFont font = workbook.createFont();
	 	 //      
	 	 //font.setFontHeightInPoints((short)10);
	 	 //    
	 	 //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
	 	 //       
	 	 font.setFontName("Courier New");
	 	 //    ; 
	 	 HSSFCellStyle style = workbook.createCellStyle();
	 	 //     ; 
	 	 style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
	 	 //       ; 
	 	 style.setBottomBorderColor(HSSFColor.BLACK.index);
	 	 //     ; 
	 	 style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
	 	 //       ; 
	 	 style.setLeftBorderColor(HSSFColor.BLACK.index);
	 	 //     ; 
	 	 style.setBorderRight(HSSFCellStyle.BORDER_THIN);
	 	 //       ; 
	 	 style.setRightBorderColor(HSSFColor.BLACK.index);
	 	 //     ; 
	 	 style.setBorderTop(HSSFCellStyle.BORDER_THIN);
	 	 //       ; 
	 	 style.setTopBorderColor(HSSFColor.BLACK.index);
	 	 //           ; 
	 	 style.setFont(font);
	 	 //      ; 
	 	 style.setWrapText(false);
	 	 //              ; 
	 	 style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	 	 //              ; 
	 	 style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
	 	 
	 	 return style;
 	
 	}
}
이 내 보 내기 에 사용 할 방법 은 다음 과 같 습 니 다.

String title = Message.getString("manifestIExportTitle");
 	String[] rowsName = new String[]{"  ","       ","    ","  ","   ","    "};
 		List<Object[]> dataList = new ArrayList<Object[]>();
 		Object[] objs = null;
 		for (int i = 0; i < manifestIMainList.size(); i++) {
 			ManifestIMain man = manifestIMainList.get(i);
 			objs = new Object[rowsName.length];
 			objs[0] = i;
 			objs[1] = man.getTranNo();
 			objs[2] = man.getBillNo();
 			objs[3] = man.getStatusFlagCnName();
 			objs[4] = man.getLoginName();
 			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 			String date = df.format(man.getModiDate());
 			objs[5] = date;
 			dataList.add(objs);
 		}
 		ExportExcel ex = new ExportExcel(title, rowsName, dataList);
 		ex.export();
List를 조립 하 는 형식 입 니 다.배열 rowsName 은 데 이 터 를 지도 하 는 표시 줄 이름 이 고 title 은 엑셀 의 제목 과 sheet 이름 을 지도 합 니 다.
이상 의 데 이 터 를 예 로 들 면 내 보 낸 결 과 는 다음 과 같다.

위 에서 말씀 드 린 것 은 편집장 님 께 서 소개 해 주신 공공 POI 내 보 내기 Excel 방법 입 니 다.여러분 께 도움 이 되 셨 으 면 좋 겠 습 니 다.궁금 한 점 이 있 으 시 면 메 시 지 를 남 겨 주세요.편집장 님 께 서 바로 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기