java 全自動生成Excel之ExcelUtil篇(上一篇的升級版 [針對實體類對象的遍歷賦值])


看了上一篇隨筆之后可以對本篇有更好的了解!

使用的poi的jar包依然是上一篇的poi-3.17.jar....

import pojo.UserPojo(上一篇里有,這里就不粘貼了!)

不廢話了,直接上菜。。。

  1 package util;
  2 
  3 import java.io.File;
  4 import java.io.FileNotFoundException;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.lang.reflect.Field;
  8 import java.text.SimpleDateFormat;
  9 import java.util.ArrayList;
 10 import java.util.Date;
 11 import java.util.List;
 12 
 13 import org.apache.poi.hssf.usermodel.HSSFCellStyle;
 14 import org.apache.poi.hssf.usermodel.HSSFSheet;
 15 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 16 import org.apache.poi.ss.usermodel.Cell;
 17 import org.apache.poi.ss.usermodel.HorizontalAlignment;
 18 import org.apache.poi.ss.usermodel.Row;
 19 
 20 import pojo.UserPojo;
 21 
 22 /**
 23  * 
 24  * @ClassName: UpdatedExcelUtil
 25  * @Description: 全自動Excel工具類(升級版)
 26  * @date 2018年6月6日
 27  *
 28  */
 29 public class UpdatedExcelUtil {
 30 
 31     /**
 32      * @注: 將此方法提取出去可以變成一個工具類
 33      * 
 34      * @Description: 得到生成的Excel,並且導出到指定的文件夾中
 35      * @Title: getExcel
 36      * @date 2018-06-06
 37      * @param sqlColumn
 38      *            數據列,對應着你需要的字段(比如:sql里面的字段 "username")
 39      * @param sqlColumnName
 40      *            數據列名,對應着你需要的字段名(比如:sql里面的字段 username的 "用戶名稱")
 41      * @param 這里我們直接傳入list(根據需要傳入什么數據---》可以是sql喲,或者其他的什么)
 42      * @param file
 43      *            文件路徑
 44      * @return void 返回類型
 45      *
 46      */
 47     public static void getExcel(String[] sqlColumn, String[] sqlColumnName, List<UserPojo> list, File file) {
 48         // 創建一個Excel
 49         @SuppressWarnings("resource")
 50         HSSFWorkbook wb = new HSSFWorkbook();
 51         // 創建工作表
 52         HSSFSheet sheet = wb.createSheet();
 53         // 創建行
 54         Row row = sheet.createRow(0);
 55 
 56         // 創建樣式
 57         HSSFCellStyle style = wb.createCellStyle();
 58         // style.setDataFormat(format.getFormat("@"));
 59 
 60         // 居中格式
 61         style.setAlignment(HorizontalAlignment.CENTER);
 62 
 63         // 創建單元格(生成動態的表頭),且讓各表頭居中顯示
 64         // Cell cell=row.createCell(0);
 65         Cell cell = null;
 66         for (int i = 0; i < sqlColumn.length; i++) {
 67             // 創建傳入進來的表頭的個數
 68             cell = row.createCell((short) i);
 69             // 表頭的值就是傳入進來的值
 70             cell.setCellValue(sqlColumnName[i]);
 71             sheet.setColumnWidth(i, 20 * 200);// 設置列寬
 72             cell.setCellStyle(style);
 73         }
 74 
 75         // list 不能為空
 76         if (list != null) {
 77             for (int i = 0; i < list.size(); i++) {
 78                 // 一組數據,新增一行
 79                 row = sheet.createRow((int) i + 1);
 80                 // 得到所有的行 一個result就代表 一行
 81                 UserPojo result = list.get(i);
 82                 // 創建 Field類,使用反射,得到實體類的屬性值
 83                 Field[] fl = result.getClass().getDeclaredFields();
 84                 // 在有所有的記錄基礎之上,遍歷傳入進來的表頭,再創建N行
 86                 for (int j = 0; j < sqlColumn.length; j++) {
 87                     // 創建單元格,根據表頭數量對應每行多少單元格數據
 88                     cell = row.createCell(j);
 89                     // 得到當i=n時,j=n時的UserPojo的第n個屬性值
 90                     Field f = fl[j];
 91                     // 允許反射時訪問私有變量
 92                     f.setAccessible(true);
 93                     Object value;
 94                     try {
 95                         // 得到當前狀態下的實體類屬性的值
 96                         value = f.get(result);
 97                         // 放入對應的單元格內
 98                         cell.setCellValue(value.toString());
 99                     } catch (IllegalArgumentException e) {
100                         e.printStackTrace();
101                     } catch (IllegalAccessException e) {
102                         e.printStackTrace();
103                     }
104 
105                 }
106             }
107         }
108 
109         try {
110             FileOutputStream fileOutputStreane = new FileOutputStream(file);
111             wb.write(fileOutputStreane);
112             fileOutputStreane.flush();
113             fileOutputStreane.close();
114         } catch (FileNotFoundException e) {
115             e.printStackTrace();
116         } catch (IOException e) {
117             e.printStackTrace();
118         }
119 
120     }
121 
122     /**
123      * 
124      * @Description: 以實現功能為主,沒有分層,一般來說這些應該處於controller里面
125      * @Title: exproExcel
126      * @date 2018-06-06 參數
127      * @return void 返回類型
128      *
129      */
130     public static void exproExcel() {
131         File file = new File("D:/" + getFileName() + ".xls");
132         String[] sqlColumn = { "uid", "uname", "upass", "udate" };
133         String[] sqlColumnName = { "人員編號", "人員姓名", "登錄密碼", "注冊時間" };
134         // 將此方法提取出去,可以生成一個util工具類
135         getExcel(sqlColumn, sqlColumnName, listUser(), file);
136     }
137 
138     /**
139      * @Description: 運行測試
140      * @author WengQuan
141      * @Title: main
142      * @date 2018-06-06
143      * @param args
144      *            參數
145      * @return void 返回類型
146      *
147      */
148     public static void main(String[] args) {
149         exproExcel();
150     }
151 
152     /**
153      * 生成一個以系統時間為文件名的字符串(精確到了毫秒)
154      */
155     public static String getFileName() {
156         SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");// 設置日期格式
157         String nowDataSystem = df.format(new Date());
158         return nowDataSystem;
159     }
160 
161     /**
162      * 
163      * @Description: 一組測試數據
164      * @Title: listUser
165      * @date 2018-06-06
166      * @return 參數
167      * @return List<UserPojo> 返回類型
168      *
169      */
170     public static List<UserPojo> listUser() {
171         List<UserPojo> list = new ArrayList<UserPojo>();
172         UserPojo up1 = new UserPojo(91, "小明", "xiaoming1", "2018、03、21");
173         UserPojo up2 = new UserPojo(100, "安妮", "anni", "2018-03-22");
174         UserPojo up3 = new UserPojo(93, "dinosaurs", "dinosaurs", "2018年03月02日");
175         list.add(up1);
176         list.add(up2);
177         list.add(up3);
178         return list;
179     }
180 }

效果截圖:

希望誰看到了哪里有問題可以聯系我,提醒我,本人以學習為主。大神請勿噴!

版權聲明:本文為博主原創文章,可以轉載,但請保留本文地址,謝謝大家!

文章地址: http://www.cnblogs.com/hotspring/

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM