POI匯出Excel(一)
阿新 • • 發佈:2019-01-11
匯出樣式如下:
========================================================================================
工具類:
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.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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 ExcelUtil1 {
/**
* 不按照實體類的欄位順序--水平排列
* 這是一個通用的方法,利用了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 exportExcelByHor(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);
//工作表列寬15位元組
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);
//將其放入map
Map<Integer,String> map = new HashMap<Integer,String>();
for(int i=0;i<headersName.length;i++){
map.put(i, headersName[i]);
}
/**
* 產生表格標題行(也就是第一行)行從0開始0-1-2-3
*/
HSSFRow row = sheet.createRow(0);
Collection<String> c = map.values();
Iterator<String> it = c.iterator();
HSSFCell cell;
int size = 0;
while(it.hasNext()){
cell = row.createCell(size);//建立單元格,並設定樣式
cell.setCellStyle(style);
cell.setCellValue(it.next());
size ++;
}//建立好了第一行(每一列的名稱)
//根據欄位寫入內容
Iterator<T> dataIt = dataset.iterator();//資料
int zdRow = 0;
while(dataIt.hasNext()){//遍歷所有記錄
zdRow ++;
row = sheet.createRow(zdRow);//內容行從1開始
int zdCell = 0;//每一個單元格從0開始
T t = dataIt.next();//獲取每一條記錄
//利用反射,動態呼叫getXxx()方法得到屬性值(可以不按照原來欄位順序)
Field[] fields = t.getClass().getDeclaredFields();
for(int k=0;k<headersId.length;k++){//遍歷欄位
for(int i=0;i<fields.length;i++){//遍歷類中所有屬性
Field field = fields[i];
//getName()方法獲得的是屬性 :id name sex
String fieldName = field.getName();
if(headersId[k].equals(fieldName)){
cell = row.createCell(zdCell);//建立每一行的單元格從0開始
cell.setCellStyle(style);
zdCell ++;
String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);//相當於getId getName getSex
Class tCls = t.getClass();
//使用反射呼叫一個方法 new Class[] {}:表示呼叫方法是傳遞的實際引數型別,若為字串則是String.class
try {
Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
//執行方法Object obj= method.invoke(物件, 引數1, 引數2...)
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";
exportExcelByHor(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;
}
}