POI匯出Excel(二)
阿新 • • 發佈:2019-01-10
匯出樣式如下:
==============================================================
工具類:
package com.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
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.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
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 com.entity.Student;
public class ExcelUtil2 {
/**
* 不按照實體類的欄位順序--垂直排列
* 這是一個通用的方法,利用了JAVA的反射機制,可以將放置在JAVA集合中並且符合一定條件的資料以 EXCEL 的形式輸出到指定IO裝置上
* @param title sheet名
* @param headersName 表頭陣列
* @param headersId 表頭所對應的欄位名稱(陣列)
* @param dataset 需要顯示的資料集合,集合中一定要放置符合javabean風格的類的物件。此方法支援的 javabean屬性的資料型別有基本資料型別及String,Date,byte[](圖片資料)
* @param out 與輸出裝置關聯的流物件,可以將EXCEL文件匯出到本地檔案或者網路中
* @param pattern 如果有時間資料,設定輸出格式一般為"yyyy-MM-dd HH:mm:ss"
* @param Excelpath 匯出Excel儲存的路徑和名稱
* 例如"C:"+File.separator+"Users"+File.separator+"Administrator"+File.separator+"Desktop"+File.separator+"學生表.xls"
* 匯出到桌面,名稱為:學生表.xls 有時候要注意匯出檔案的名稱不要重複
*/
public static<T> void exportExcelVert(String title, String[] headersName,String[] headersId,
Collection<T> dataset,OutputStream out, String pattern,String excelPath) {
// 宣告一個工作薄
HSSFWorkbook wb = new HSSFWorkbook();
//宣告一個工作表(sheet名稱)
HSSFSheet sheet = wb.createSheet(title);
//工作表列寬20位元組
sheet.setDefaultColumnWidth(20);
//建立單元格樣式
HSSFCellStyle style = wb.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);//左右居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//上下居中
//生成一個字型
HSSFFont font = wb.createFont();
//font.setColor(HSSFColor.VIOLET.index);//顏色
font.setFontHeightInPoints((short) 12);//字號
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);//加粗
// 把字型應用到當前的樣式
style.setFont(font);
HSSFRow row; //行
HSSFCell cell;//每一個單元格
//遍歷列名
for(int i=0;i<headersName.length;i++){
row = sheet.createRow(i);//建立行
cell = row.createCell(0);//建立第一個單元格
cell.setCellStyle(style);
cell.setCellValue(headersName[i]);
Iterator<T> dataIt = dataset.iterator();//資料
//每一行的資料從1開始
int k = 0;//記錄Cell
while(dataIt.hasNext()){
//獲取每一條記錄
T t = dataIt.next();
//利用反射
Field[] fields = t.getClass().getDeclaredFields();
for(int n=0;n<fields.length;n++){//遍歷類中所有屬性
Field field = fields[n];
String fieldName = field.getName();//id name sex 等
if(headersId[i].equals(fieldName)){
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
//建立行和單元格
cell = row.createCell(++k);
cell.setCellStyle(style);
Class tCls = t.getClass();
try {
Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
HSSFRichTextString textValue = null;
if (value instanceof Integer) {//整數
int intValue = (Integer) value;
cell.setCellValue(intValue);
} else if (value instanceof Float) {//float小數
float fValue = (Float) value;
textValue = new HSSFRichTextString(String.valueOf(fValue));
cell.setCellValue(textValue);
} else if (value instanceof Double) {//double小數
double dValue = (Double) value;
textValue = new HSSFRichTextString(String.valueOf(dValue));
cell.setCellValue(textValue);
} else if (value instanceof Long) {//long型別
long longValue = (Long) value;
cell.setCellValue(longValue);
} else if (value instanceof Boolean) {//boolean
boolean bValue = (Boolean) value;
String sex = (bValue==true? "男":"女");
cell.setCellValue(sex);
} else if (value instanceof Date) {//java.util.Date
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
cell.setCellValue(sdf.format(date));
} else{//其它資料型別都當作字串簡單處理
cell.setCellValue(value.toString());
}
break;
} catch (NoSuchMethodException | SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
}
}
//迴圈完畢--預設匯出到桌面
try {
out = new FileOutputStream(excelPath);
wb.write(out);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//測試
public static void main(String[] args) {
/*==============模擬資料=================*/
List<Student> list = new ArrayList<Student>();
list.add(new Student(111,"張三","男",22,"北京",4000.0,200.5,new Date()));
list.add(new Student(222,"李四","男",23,"長沙",450.56,100.5,new Date()));
list.add(new Student(333,"莉莉絲","女",24,"成都",8888.8,200.0,new Date()));
list.add(new Student(444,"紅蓮","女",25,"上海",666.66,150.0,new Date()));
list.add(new Student(555,"丹丹","女",26,"湖北",5000.50,200.0,new Date()));
/*==============模擬資料=================*/
String title = "2017名單";//匯出Excel表名
//儲存路徑
String path = "C:"+File.separator+"Users"+File.separator+"Administrator"+
File.separator+"Desktop"+File.separator+"測試垂直"+System.currentTimeMillis()+".xls";
//匯出部分欄位且打亂欄位順序
String[] headersName = {"年齡","性別","家庭住址","錄入時間","姓名"};//表頭的名字
String[] headersId = {"age","sex","address","createTime","name"};//表頭對應的欄位名
FileOutputStream out = null;//輸出流
String pattern = "yyyy-MM-dd HH:mm:ss";
exportExcelVert(title, headersName, headersId, list, out, pattern, path);
}
}
====================================================
實體類:學生
package com.entity; import java.io.Serializable; import java.util.Date; public class Student implements Serializable { private Integer id; private String name; private String sex; private Integer age; private String address; private Double sal; private Double comm; private Date createTime; public Student(){} public Student(Integer id, String name, String sex, Integer age, String address, Double sal, Double comm, Date createTime) { super(); this.id = id; this.name = name; this.sex = sex; this.age = age; this.address = address; this.sal = sal; this.comm = comm; this.createTime = createTime; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } 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 Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Double getSal() { return sal; } public void setSal(Double sal) { this.sal = sal; } public Double getComm() { return comm; } public void setComm(Double comm) { this.comm = comm; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } }