apache POI 내 보 내기 Excel

웹 개발 에서 데이터 가 져 오기 내 보 내기 라 는 전형 적 인 기능 이 있 습 니 다.특히 데이터 의 도 출 은 생산 관리 나 재무 시스템 에서 매우 보편적으로 사용 되 는데 이런 시스템 들 은 보고서 인쇄 작업 을 자주 해 야 하기 때문이다.데이터 내 보 내기 형식 은 보통 Excel 이나 PDF 입 니 다.
 
우선 엑셀 형식의 파일 을 내 보 냅 시다.현재 주 류 는 Excel 파일 을 조작 하 는 오픈 소스 도구 가 매우 많 습 니 다. 많이 사용 하 는 것 이 바로 Apache 의 POI 와 JExcelAPI 입 니 다. 여 기 는 Apache POI 를 사용 합 니 다.
 
 
package org.cric.util;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFClientAnchor;
import org.apache.poi.hssf.usermodel.HSSFComment;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPatriarch;
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.HSSFColor;

/**
 *       POI3.7    EXCEL  
 * @author Administrator
 *
 * @param <T>     ,      javabean    
 *           ,boolean   xxx get   getXxx(),   isXxx()
 * byte[] jpg       
 */
public class ExportExcel<T> {
	
	public void exportExcel(Collection<T> dataset,OutputStream out){
		this.exportExcel("  POI  EXCEL  ", null, dataset, out, "yyyy-MM-dd");
	}
	
	public void exportExcel(String[] headers,Collection<T> dataset,OutputStream out){
		this.exportExcel("  POI  EXCEL  ", headers, dataset, out,"yyyy-MM-dd");
	}
	
	public void exportExcep(String[] headers,Collection<T> dataset,OutputStream out,String patterm){
		this.exportExcel("  POI  EXCEL  ", headers, dataset, out, patterm);
	}
	
	/**
	 *          ,   JAVA     ,      JAVA               EXCEL        IO   
	 * @param title
	 *  	     
	 * @param headers
	 * 		        
	 * @param dataset
	 * 		         ,          javabean       。      
	 * 		javabean               String,Date,byte[](    )
	 * @param out
	 * 		           ,   EXCEL              
	 * @param pattem
	 * 		       ,      。   "yyyy-MM-dd";
	 */
	public void exportExcel(String title,String[] headers,Collection<T> dataset,OutputStream out,String pattem){
		//       
		HSSFWorkbook workbook = new HSSFWorkbook();
		//      
		HSSFSheet sheet = workbook.createSheet(title);
		//          15   
		sheet.setDefaultColumnWidth(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("wuhaidong");
		
		//       
		HSSFRow row = sheet.createRow(0);
		for(int 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(int 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);
				Class tCls = t.getClass();
				try {
					Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
					Object value = getMethod.invoke(t, new Object[]{});
					//                
					String textValue = null;
					/*if(value instanceof Integer){
						Integer intValue = (Integer)value;
						cell.setCellValue(intValue);
					}else if(value instanceof Float){
						Float floatValue = (Float)value;
						cell.setCellValue(floatValue);
					}else if(value instanceof Double){
						Double doubleValue = (Double)value;
						cell.setCellValue(doubleValue);
					}else if(value instanceof Long){
						Long longValue = (Long)value;
						cell.setCellValue(longValue);
					}else */
					if(value instanceof Boolean){
						boolean booleanValue = (Boolean)value;
						textValue = " ";
						if(!booleanValue){
							textValue = " ";
						}
						cell.setCellValue(textValue);
					}else if(value instanceof Date){
						Date date = (Date)value;
						SimpleDateFormat sdf = new SimpleDateFormat(pattem);
						textValue = sdf.format(date);
						cell.setCellValue(textValue);
					}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,55,(short)6,index,(short)6,index);
						anchor.setAnchorType(2);
						patriarch.createPicture(anchor,workbook.addPicture(bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
					}else{
						//                
						textValue = 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{
					//    
				}
			}
		}
		try {
			workbook.write(out);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


 
 
 
package org.cric.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.swing.JOptionPane;
import org.leno.export.util.Student;
public class ExportExcelTest {

	public static void main(String[] args) {
		
		ExportExcel<Student> exportExcel = new ExportExcel<Student>();
		
		String[] headers = new String[]{"  ","  ","  ","  ","    "};
		
		Student stu = new Student(1000,"  ",23,true, new Date());
		Student stu2 = new Student(1001,"  ",22,false,new Date());
		Student stu3 = new Student(1002,"  ",24,true,new Date());
		Student stu4 = new Student(1003,"  ",22,true,new Date());
		List<Student> studentList = new ArrayList<Student>();
		studentList.add(stu);
		studentList.add(stu2);
		studentList.add(stu3);
		studentList.add(stu4);
		
		FileOutputStream out = null;
		try {
			out = new FileOutputStream("E:\\  .xls");
			exportExcel.exportExcep(headers, studentList, out, "yyyy-MM-dd");
			JOptionPane.showMessageDialog(null, "    ");
			System.out.println("EXCEL    !");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}finally{
			if(null != out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

좋은 웹페이지 즐겨찾기