[TOC]java
最近項目中遇到要將MySQL數據庫中的某些數據導出爲Excel格式保存,在之前也寫過這樣的功能,此次就準備用之前的代碼,可是看了一下,此次卻不同,由於在之前用到的都是導出一種或幾種數據,種類很少,可是此次導出的種類比較多,至關於就是每一種類型的數據得單獨寫一些代碼,並且重複的比較多;就想寫一個通用的,無論什麼種類,直接傳入數據就好了;git
由於數據的種類是不一樣的,裏面的屬性也各不相同,如何用同一段代碼去處理這些不一樣種類的屬性,讓我第一時間想到了Java的泛型和反射;由於以前的筆記中就寫到了反射,這時候恰好派上用場,就來實際操做一下;github
首先導入poi相應的jar包:數據庫
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.17</version>
</dependency>
複製代碼
/** * @author gyc * @date 2018/10/26 21:50 */
public class PojoA {
private String name;
private int num;
private double price;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
複製代碼
pojoB:apache
/** * @author gyc * @date 2018/10/26 21:51 */
public class PojoB {
private String userName;
private int age;
private Date birthday;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
}
複製代碼
/** * @author gyc * @date 2018/10/26 21:45 */
public class ExcelUtil<T> {
public HSSFWorkbook setExcel(String title,String[] columnNames, List<T> tList) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, IOException {
// 1.建立Excel工做薄對象
HSSFWorkbook workbook=new HSSFWorkbook();
// 2.建立Excel工做表對象
HSSFSheet sheet=workbook.createSheet(title);
HSSFRow row=null;
// 3.建立Excel工做表的第一行,並填充列名
row=sheet.createRow(0);
for(int i=0;i<columnNames.length;i++){
row.createCell(i).setCellValue(columnNames[i]);
}
Field[] declaredFields = tList.get(0).getClass().getDeclaredFields();
// 4.將數據填充至表格中
for(int j=1;j<=tList.size();j++){
T t= tList.get(j-1);
row=sheet.createRow(j);
for(int i=0;i<declaredFields.length;i++){
// 經過反射獲取屬性值
String fieldName = declaredFields[i].getName();
String getMethodName="get"+fieldName.substring(0,1).toUpperCase()+fieldName.substring(1);
Method declaredMethod = t.getClass().getDeclaredMethod(getMethodName);
//執行方法
Object fieldValue = declaredMethod.invoke(t);
//判斷是否爲空
if(fieldValue!=null && !"".equals(fieldValue)){
//判斷屬性值類型
if(fieldValue instanceof Integer){
row.createCell(i).setCellValue(Integer.valueOf(fieldValue.toString()));
}else if(fieldValue instanceof Double){
row.createCell(i).setCellValue(Double.valueOf(fieldValue.toString()));
}else if(fieldValue instanceof Date){
row.createCell(i).setCellValue(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(fieldValue));
}else {
row.createCell(i).setCellValue(fieldValue.toString());
}
}else {
row.createCell(i).setCellValue("");
}
}
}
// 自動設置列寬,要在在數據讀入以後設置;
for (int i = 0; i < columnNames.length; i++) {
sheet.autoSizeColumn(i);
//在自動適應的基礎上增長寬度
// sheet.setColumnWidth(i,sheet.getColumnWidth(i)*17/10);
}
return workbook;
}
}
複製代碼
測試代碼數組
/** * @author gyc * @date 2018/10/26 21:52 */
public class Test {
public static void main(String[] args) throws InvocationTargetException, NoSuchMethodException, IllegalAccessException, IOException {
PojoA pojoA=new PojoA();
pojoA.setName("a");
pojoA.setNum(1);
pojoA.setPrice(1.1234);
List<PojoA> lista=new ArrayList<>();
lista.add(pojoA);
PojoB pojoB=new PojoB();
pojoB.setUserName("b");
pojoB.setAge(2);
pojoB.setBirthday(new Date());
List<PojoB> listb=new ArrayList<>();
listb.add(pojoB);
HSSFWorkbook workbooka = new ExcelUtil().setExcel("pojoA", new String[]{"名稱", "數量", "價格"}, lista);
HSSFWorkbook workbookb = new ExcelUtil().setExcel("pojoB", new String[]{"名稱", "年齡", "時間"}, listb);
workbooka.write(new FileOutputStream(new File("/Users/rose/IdeaProjects/java-study/smalltools/pojoA.xls")));
workbookb.write(new FileOutputStream(new File("/Users/rose/IdeaProjects/java-study/smalltools/pojoB.xls")));
}
}
複製代碼
本篇筆記中使用了Java泛型和反射,但都是用得比較淺,只是最基礎的使用;主要解決了處理數據種類繁多的的問題,不用單獨處理; 其中也有不少不足之處,以下:this