java 生成EXCEL完整實現(附加代碼)

生成Excel 我這裏是用的POI 的jar包      請尊重原創,轉載時請標明出處 謝謝

需要的jar包 請自行下載 

commons-beanutils-1.7.1.jar

commons-lang-2.1.jar

poi-3.10.jar


實體類:

import java.util.Date;

public class Student {
	private String name;
	private String sex;
	private Date age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Date getAge() {
		return age;
	}
	public void setAge(Date age) {
		this.age = age;
	}
}


測試類:

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class ExportExcelMain {
	
	public static String xlsFile="F:\\excel\\test.xls"; //產生的Excel文件的名稱
	
	/**
	 * 
	 * 方法描述: main方法
	 * @param args  void
	 * @author Andy  2014-4-29  下午05:42:03
	 */
	public static void main(String[] args) {
		try {
			FileOutputStream os = new FileOutputStream(xlsFile);
			String[] strMeaning={"名稱","性別","年齡"};
			String[] strName={"name","sex","age"};
			List<Student> ls=new ArrayList<Student>();
			for(int i=0;i<3;i++){
				Student s=new Student();
				s.setName("我的名稱"+i);
				s.setSex("我的性別"+i);
				s.setAge(new Date());
				ls.add(s);
			}
			System.out.println("進入導出方法");
			ExportExcel.exportExcel(strMeaning, strName, ls, os);
		} catch (Exception  e1){
			e1.getStackTrace();
		}
	}
}


生成Excel類:

import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
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.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;

public class ExportExcel {
	
	private static SimpleDateFormat SDF = null;
	
	/**
	 * 
	 * 方法描述:生成調用的方法
	 * @param strMeaning	表頭的數組
	 * @param strName		表字段數組
	 * @param collection	表數據集合
	 * @param os			輸出流
	 * @throws Exception  void
	 * @author Andy  2014-4-29  下午05:40:57
	 */
	public static void exportExcel(String[] strMeaning,String[] strName,Collection<?> collection,OutputStream os) throws Exception{
		HSSFWorkbook wb = ExportExcel.generateExcelforObject(strMeaning,strName,"",collection);
		wb.write(os);
	}
	
	private static HSSFWorkbook generateExcelforObject(String[] strMeaning,String[] strName,String str,Collection<?> collection) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
		HSSFWorkbook wb = new HSSFWorkbook();
		if(collection==null || collection.size()<1)return wb; //無數據側返回
		if(strMeaning==null || strMeaning.length<1)return wb; //表頭爲空側返回
		if(strName==null || strName.length<1)return wb;    //字段側返回
		if(strMeaning.length!=strName.length)return wb;    //兩個數組長度不同側返回
		HSSFRow row=null;
		short rowNum = 0;
		//設置工作簿的名稱
		String sheetTitle=StringUtils.isEmpty(str)?"Sheet1":str;
		HSSFSheet sheet = wb.createSheet();
		wb.setSheetName(0,sheetTitle);
		//設置標題
		row = sheet.createRow(rowNum);
		setTitle(row, strMeaning,wb);
		for (Iterator<?> iter = collection.iterator(); iter.hasNext();) {
			Object exportEle = iter.next();
			// 行對象
			row = sheet.createRow(++rowNum);
			//設置對應值
			setRow(row, strName, exportEle);
		}
		return wb;
	}
	
	/**
	 * 方法描述: 爲Excel頁中的每個橫行設置標題
	 * @param row
	 * @param strMeaning
	 * @param wb
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException  void
	 * @author Andy  2014-4-29  下午05:45:45
	 */
	@SuppressWarnings("deprecation")
	private static void setTitle(HSSFRow row,String[] strMeaning,HSSFWorkbook wb) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		HSSFCellStyle style = wb.createCellStyle();
	    // 設置這些樣式
	    style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.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 = wb.createFont();
//	    font.setColor(HSSFColor.WHITE.index);  //設置字體顏色
	    font.setFontHeightInPoints((short)10);
//	    font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);  //設置字體加粗
	    // 把字體應用到當前的樣式
	    style.setFont(font);
		for (int k = 0; k < strMeaning.length; k++) {
			HSSFCell cell = row.createCell((short)k);
			cell.setCellStyle(style);
			cell.setCellValue(strMeaning[k]);
		}
	}
	
	/**
	 * 
	 * 方法描述: 爲Excel頁中的每個橫行設置值
	 * @param row
	 * @param strName
	 * @param exportModel
	 * @throws IllegalAccessException
	 * @throws InvocationTargetException
	 * @throws NoSuchMethodException  void
	 * @author Andy  2014-4-29  下午05:44:02
	 */
	@SuppressWarnings("deprecation")
	private static void setRow(HSSFRow row,String[] strName,Object exportModel) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{
		Object temp=null;
		for (int k = 0; k < strName.length; k++) {
			// Cell對象
			HSSFCell cell = row.createCell((short) k);
			//設置對應值
			try {
				//檢查該實體是否有這個屬性
				temp = PropertyUtils.getProperty(exportModel, strName[k]);
			} catch (Exception e) {
				e.getStackTrace();
				continue;
			}
			if(temp==null){
				cell.setCellValue(StringUtils.EMPTY);
			}else{ 
				if(temp instanceof Date){
					cell.setCellValue(getDateTimeFormat().format(Date.class.cast(temp)));
				}else if(NumberUtils.isNumber(temp.toString())){
					cell.setCellValue(Double.parseDouble(temp.toString()));
				}else{
					cell.setCellValue(temp.toString());
				}
			}
		}
	}
	
	/**
	 * 方法描述: 獲取系統時間格式
	 * @return  SimpleDateFormat
	 * @author Andy  2014-4-29  下午05:44:39
	 */
	public static SimpleDateFormat getDateFormat(){
		if(SDF==null){SDF=new SimpleDateFormat("yyyy-MM-dd");}
		return SDF;
	}

	/**
	 * 方法描述: 獲取系統精確時間格式
	 * @return  SimpleDateFormat
	 * @author Andy  2014-4-29  下午05:44:27
	 */
	public static SimpleDateFormat getDateTimeFormat(){
		if(SDF==null){SDF=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");}
		return SDF;
	}
	
}



請尊重原創,轉載時請標明出處 . O(∩_∩)O謝謝~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章