一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - Springboot使用POI實現導出Excel文件示例

Springboot使用POI實現導出Excel文件示例

2020-08-21 11:27知識林 Java教程

本篇文章主要介紹了Springboot使用POI實現導出Excel文件示例,非常具有實用價值,需要的朋友可以參考下。

前面講述了使用POI導出Word文件和讀取Excel文件,這兩個例子都相對簡單,接下來要講述的使用POI導出Excel文件要復雜得多,內容也會比較長。

創建表頭信息

表頭信息用于自動生成表頭結構及排序

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class ExcelHeader implements Comparable<ExcelHeader>{
 /**
  * excel的標題名稱
  */
 private String title;
 /**
  * 每一個標題的順序
  */
 private int order;
 /**
  * 說對應方法名稱
  */
 private String methodName;
 
 
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public int getOrder() {
  return order;
 }
 public void setOrder(int order) {
  this.order = order;
 }
 public String getMethodName() {
  return methodName;
 }
 public void setMethodName(String methodName) {
  this.methodName = methodName;
 }
 
 public int compareTo(ExcelHeader o) {
  return order>o.order?1:(order<o.order?-1:0);
 }
 public ExcelHeader(String title, int order, String methodName) {
  super();
  this.title = title;
  this.order = order;
  this.methodName = methodName;
 }
}

表頭信息的Annotation

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/**
 * 用來在對象的get方法上加入的annotation,通過該annotation說明某個屬性所對應的標題
 * Created by 鐘述林 on 2016/10/29 0:14.
 */
@Retention(RetentionPolicy.RUNTIME)
public @interface ExcelResources {
 /**
  * 屬性的標題名稱
  * @return
  */
 String title();
 /**
  * 在excel的順序
  * @return
  */
 int order() default 9999;
}

創建數據實體

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
public class WebDto {
 
 //網站名稱
 private String name;
 
 //網址
 private String url;
 
 //用戶名
 private String username;
 
 //密碼
 private String password;
 
 //日均訪問量
 private Integer readCount;
 
 public WebDto(String name, String url, String username, String password, Integer readCount) {
  this.name = name;
  this.url = url;
  this.username = username;
  this.password = password;
  this.readCount = readCount;
 }
 
 public WebDto() {}
 
 @Override
 public String toString() {
  return "WebDto{" +
    "name='" + name + '\'' +
    ", url='" + url + '\'' +
    ", username='" + username + '\'' +
    ", password='" + password + '\'' +
    ", readCount=" + readCount +
    '}';
 }
 
 @ExcelResources(title="網站名稱",order=1)
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }
 
 @ExcelResources(title="網址",order=2)
 public String getUrl() {
  return url;
 }
 
 public void setUrl(String url) {
  this.url = url;
 }
 
 @ExcelResources(title="用戶名",order=3)
 public String getUsername() {
  return username;
 }
 
 public void setUsername(String username) {
  this.username = username;
 }
 
 @ExcelResources(title="密碼",order=4)
 public String getPassword() {
  return password;
 }
 
 public void setPassword(String password) {
  this.password = password;
 }
 
 @ExcelResources(title="日均訪問量",order=5)
 public Integer getReadCount() {
  return readCount;
 }
 
 public void setReadCount(Integer readCount) {
  this.readCount = readCount;
 }
}

注意:這里使用到了@ExcelResources來自動識別表頭信息及序號

獲取模板文件的工具類

?
1
2
3
4
5
6
public class TemplateFileUtil {
 
 public static FileInputStream getTemplates(String tempName) throws FileNotFoundException {
  return new FileInputStream(ResourceUtils.getFile("classpath:excel-templates/"+tempName));
 }
}

注意:從這里可以看出,所有的Excel模板文件都放在resources/excel-templates/目錄下。

模板工具類

通過此類可以自動復制表樣式等功能

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
/**
 * 該類實現了基于模板的導出
 * 如果要導出序號,需要在excel中定義一個標識為sernums
 * 如果要替換信息,需要傳入一個Map,這個map中存儲著要替換信息的值,在excel中通過#來開頭
 * 要從哪一行那一列開始替換需要定義一個標識為datas
 * 如果要設定相應的樣式,可以在該行使用styles完成設定,此時所有此行都使用該樣式
 * 如果使用defaultStyls作為表示,表示默認樣式,如果沒有defaultStyles使用datas行作為默認樣式
 * Created by 鐘述林 [email protected] on 2016/10/28 23:38.
 */
public class ExcelTemplate {
 
 /**
  * 數據行標識
  */
 public final static String DATA_LINE = "datas";
 /**
  * 默認樣式標識
  */
 public final static String DEFAULT_STYLE = "defaultStyles";
 /**
  * 行樣式標識
  */
 public final static String STYLE = "styles";
 /**
  * 插入序號樣式標識
  */
 public final static String SER_NUM = "sernums";
 private static ExcelTemplate et = new ExcelTemplate();
 private Workbook wb;
 private Sheet sheet;
 /**
  * 數據的初始化列數
  */
 private int initColIndex;
 /**
  * 數據的初始化行數
  */
 private int initRowIndex;
 /**
  * 當前列數
  */
 private int curColIndex;
 /**
  * 當前行數
  */
 private int curRowIndex;
 /**
  * 當前行對象
  */
 private Row curRow;
 /**
  * 最后一行的數據
  */
 private int lastRowIndex;
 /**
  * 默認樣式
  */
 private CellStyle defaultStyle;
 /**
  * 默認行高
  */
 private float rowHeight;
 /**
  * 存儲某一方所對于的樣式
  */
 private Map<Integer,CellStyle> styles;
 /**
  * 序號的列
  */
 private int serColIndex;
 private ExcelTemplate(){
 
 }
 public static ExcelTemplate getInstance() {
  return et;
 }
 
 /**
  * 從classpath路徑下讀取相應的模板文件
  * @param path
  * @return
  */
 public ExcelTemplate readTemplateByClasspath(String path) {
  try {
   wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
   initTemplate();
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("讀取模板不存在!請檢查");
  }
  return this;
 }
 /**
  * 將文件寫到相應的路徑下
  * @param filepath
  */
 public void writeToFile(String filepath) {
  FileOutputStream fos = null;
  try {
   fos = new FileOutputStream(filepath);
   wb.write(fos);
  } catch (FileNotFoundException e) {
   e.printStackTrace();
   throw new RuntimeException("寫入的文件不存在");
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("寫入數據失敗:"+e.getMessage());
  } finally {
   try {
    if(fos!=null) fos.close();
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
 /**
  * 將文件寫到某個輸出流中
  * @param os
  */
 public void wirteToStream(OutputStream os) {
  try {
   wb.write(os);
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("寫入流失敗:"+e.getMessage());
  }
 }
 /**
  * 從某個路徑來讀取模板
  * @param path
  * @return
  */
 public ExcelTemplate readTemplateByPath(String path) {
  try {
   wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
   initTemplate();
  } catch (IOException e) {
   e.printStackTrace();
   throw new RuntimeException("讀取模板不存在!請檢查");
  }
  return this;
 }
 
 /**
  * 創建相應的元素,基于String類型
  * @param value
  */
 public void createCell(String value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(int value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue((int)value);
  curColIndex++;
 }
 public void createCell(Date value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(double value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(boolean value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 
 public void createCell(Calendar value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value);
  curColIndex++;
 }
 public void createCell(BigInteger value) {
  Cell c = curRow.createCell(curColIndex);
  setCellStyle(c);
  c.setCellValue(value==null?0:value.intValue());
  curColIndex++;
 }
 /**
  * 設置某個元素的樣式
  * @param c
  */
 private void setCellStyle(Cell c) {
  if(styles.containsKey(curColIndex)) {
   c.setCellStyle(styles.get(curColIndex));
  } else {
   c.setCellStyle(defaultStyle);
  }
 }
 /**
  * 創建新行,在使用時只要添加完一行,需要調用該方法創建
  */
 public void createNewRow() {
  if(lastRowIndex>curRowIndex&&curRowIndex!=initRowIndex) {
   sheet.shiftRows(curRowIndex, lastRowIndex, 1,true,true);
   lastRowIndex++;
  }
  curRow = sheet.createRow(curRowIndex);
  curRow.setHeightInPoints(rowHeight);
  curRowIndex++;
  curColIndex = initColIndex;
 }
 
 /**
  * 插入序號,會自動找相應的序號標示的位置完成插入
  */
 public void insertSer() {
  int index = 1;
  Row row = null;
  Cell c = null;
  for(int i=initRowIndex;i<curRowIndex;i++) {
   row = sheet.getRow(i);
   c = row.createCell(serColIndex);
   setCellStyle(c);
   c.setCellValue(index++);
  }
 }
 /**
  * 根據map替換相應的常量,通過Map中的值來替換#開頭的值
  * @param datas
  */
 public void replaceFinalData(Map<String,String> datas) {
  if(datas==null) return;
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.startsWith("#")) {
     if(datas.containsKey(str.substring(1))) {
      c.setCellValue(datas.get(str.substring(1)));
     }
    }
   }
  }
 }
 /**
  * 基于Properties的替換,依然也是替換#開始的
  * @param prop
  */
 public void replaceFinalData(Properties prop) {
  if(prop==null) return;
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.startsWith("#")) {
     if(prop.containsKey(str.substring(1))) {
      c.setCellValue(prop.getProperty(str.substring(1)));
     }
    }
   }
  }
 }
 
 private void initTemplate() {
  sheet = wb.getSheetAt(0);
  initConfigData();
  lastRowIndex = sheet.getLastRowNum();
  curRow = sheet.createRow(curRowIndex);
 }
 /**
  * 初始化數據信息
  */
 private void initConfigData() {
  boolean findData = false;
  boolean findSer = false;
  for(Row row:sheet) {
   if(findData) break;
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.equals(SER_NUM)) {
     serColIndex = c.getColumnIndex();
     findSer = true;
    }
    if(str.equals(DATA_LINE)) {
     initColIndex = c.getColumnIndex();
     initRowIndex = row.getRowNum();
     curColIndex = initColIndex;
     curRowIndex = initRowIndex;
     findData = true;
     defaultStyle = c.getCellStyle();
     rowHeight = row.getHeightInPoints();
     initStyles();
     break;
    }
   }
  }
  if(!findSer) {
   initSer();
  }
 }
 /**
  * 初始化序號位置
  */
 private void initSer() {
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.equals(SER_NUM)) {
     serColIndex = c.getColumnIndex();
    }
   }
  }
 }
 /**
  * 初始化樣式信息
  */
 private void initStyles() {
  styles = new HashMap<Integer, CellStyle>();
  for(Row row:sheet) {
   for(Cell c:row) {
//    if(c.getCellType()!=Cell.CELL_TYPE_STRING) continue;
    String str = c.getStringCellValue().trim();
    if(str.equals(DEFAULT_STYLE)) {
     defaultStyle = c.getCellStyle();
    }
    if(str.equals(STYLE)) {
     styles.put(c.getColumnIndex(), c.getCellStyle());
    }
   }
  }
 }
}

操作工具類

?
    • 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      26
      27
      28
      29
      30
      31
      32
      33
      34
      35
      36
      37
      38
      39
      40
      41
      42
      43
      44
      45
      46
      47
      48
      49
      50
      51
      52
      53
      54
      55
      56
      57
      58
      59
      60
      61
      62
      63
      64
      65
      66
      67
      68
      69
      70
      71
      72
      73
      74
      75
      76
      77
      78
      79
      80
      81
      82
      83
      84
      85
      86
      87
      88
      89
      90
      91
      92
      93
      94
      95
      96
      97
      98
      99
      100
      101
      102
      103
      104
      105
      106
      107
      108
      109
      110
      111
      112
      113
      114
      115
      116
      117
      118
      119
      120
      121
      122
      123
      124
      125
      126
      127
      128
      129
      130
      131
      132
      133
      134
      135
      136
      137
      138
      139
      140
      141
      142
      143
      144
      145
      146
      147
      148
      149
      150
      151
      152
      153
      154
      155
      156
      157
      158
      159
      160
      161
      162
      163
      164
      165
      166
      167
      168
      169
      170
      171
      172
      173
      174
      175
      176
      177
      178
      179
      180
      181
      182
      183
      184
      185
      186
      187
      188
      189
      190
      191
      192
      193
      194
      195
      196
      197
      198
      199
      200
      201
      202
      203
      204
      205
      206
      207
      208
      209
      210
      211
      212
      213
      214
      215
      216
      217
      218
      219
      220
      221
      222
      223
      224
      225
      226
      227
      228
      229
      230
      231
      232
      233
      234
      235
      236
      237
      238
      239
      240
      241
      242
      243
      244
      245
      246
      247
      248
      249
      250
      251
      252
      253
      254
      255
      256
      257
      258
      259
      260
      261
      262
      263
      264
      265
      266
      267
      268
      269
      270
      271
      272
      273
      274
      275
      276
      277
      278
      279
      280
      281
      282
      283
      284
      285
      286
      287
      288
      289
      290
      291
      292
      293
      294
      295
      296
      297
      298
      299
      300
      301
      302
      303
      304
      305
      306
      307
      308
      309
      310
      311
      312
      313
      314
      315
      316
      317
      318
      319
      320
      321
      322
      323
      324
      325
      326
      327
      328
      329
      /**
       * 該類實現了將一組對象轉換為Excel表格,并且可以從Excel表格中讀取到一組List對象中
       * 該類利用了BeanUtils框架中的反射完成
       * 使用該類的前提,在相應的實體對象上通過ExcelReources來完成相應的注解
       * Created by 鐘述林 [email protected] on 2016/10/29 0:15.
       */
      public class ExcelUtil {
       private static ExcelUtil eu = new ExcelUtil();
       private ExcelUtil(){}
       
       public static ExcelUtil getInstance() {
        return eu;
       }
       /**
        * 處理對象轉換為Excel
        * @param template
        * @param objs
        * @param clz
        * @param isClasspath
        * @return
        */
       private ExcelTemplate handlerObj2Excel (String template, List objs, Class clz, boolean isClasspath) {
        ExcelTemplate et = ExcelTemplate.getInstance();
        try {
         if(isClasspath) {
          et.readTemplateByClasspath(template);
         } else {
          et.readTemplateByPath(template);
         }
         List<ExcelHeader> headers = getHeaderList(clz);
         Collections.sort(headers);
         //輸出標題
         et.createNewRow();
         for(ExcelHeader eh:headers) {
          et.createCell(eh.getTitle());
         }
         //輸出值
         for(Object obj:objs) {
          et.createNewRow();
          for(ExcelHeader eh:headers) {
           //    Method m = clz.getDeclaredMethod(mn);
           //    Object rel = m.invoke(obj);
           et.createCell(BeanUtils.getProperty(obj,getMethodName(eh)));
          }
         }
        } catch (IllegalAccessException e) {
         e.printStackTrace();
        } catch (InvocationTargetException e) {
         e.printStackTrace();
        } catch (NoSuchMethodException e) {
         e.printStackTrace();
        }
        return et;
       }
       /**
        * 根據標題獲取相應的方法名稱
        * @param eh
        * @return
        */
       private String getMethodName(ExcelHeader eh) {
        String mn = eh.getMethodName().substring(3);
        mn = mn.substring(0,1).toLowerCase()+mn.substring(1);
        return mn;
       }
       /**
        * 將對象轉換為Excel并且導出,該方法是基于模板的導出,導出到流
        * @param datas 模板中的替換的常量數據
        * @param template 模板路徑
        * @param os 輸出流
        * @param objs 對象列表
        * @param clz 對象的類型
        * @param isClasspath 模板是否在classPath路徑下
        */
       public void exportObj2ExcelByTemplate(Map<String,String> datas, String template, OutputStream os, List objs, Class clz, boolean isClasspath) {
        try {
         ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
         et.replaceFinalData(datas);
         et.wirteToStream(os);
         os.flush();
         os.close();
        } catch (IOException e) {
         e.printStackTrace();
        }
       }
       /**
        * 將對象轉換為Excel并且導出,該方法是基于模板的導出,導出到一個具體的路徑中
        * @param datas 模板中的替換的常量數據
        * @param template 模板路徑
        * @param outPath 輸出路徑
        * @param objs 對象列表
        * @param clz 對象的類型
        * @param isClasspath 模板是否在classPath路徑下
        */
       public void exportObj2ExcelByTemplate(Map<String,String> datas,String template,String outPath,List objs,Class clz,boolean isClasspath) {
        ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
        et.replaceFinalData(datas);
        et.writeToFile(outPath);
       }
       
       /**
        * 將對象轉換為Excel并且導出,該方法是基于模板的導出,導出到流,基于Properties作為常量數據
        * @param prop 基于Properties的常量數據模型
        * @param template 模板路徑
        * @param os 輸出流
        * @param objs 對象列表
        * @param clz 對象的類型
        * @param isClasspath 模板是否在classPath路徑下
        */
       public void exportObj2ExcelByTemplate(Properties prop, String template, OutputStream os, List objs, Class clz, boolean isClasspath) {
        ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
        et.replaceFinalData(prop);
        et.wirteToStream(os);
       }
       /**
        * 將對象轉換為Excel并且導出,該方法是基于模板的導出,導出到一個具體的路徑中,基于Properties作為常量數據
        * @param prop 基于Properties的常量數據模型
        * @param template 模板路徑
        * @param outPath 輸出路徑
        * @param objs 對象列表
        * @param clz 對象的類型
        * @param isClasspath 模板是否在classPath路徑下
        */
       public void exportObj2ExcelByTemplate(Properties prop,String template,String outPath,List objs,Class clz,boolean isClasspath) {
        ExcelTemplate et = handlerObj2Excel(template, objs, clz, isClasspath);
        et.replaceFinalData(prop);
        et.writeToFile(outPath);
       }
       
       private Workbook handleObj2Excel(List objs, Class clz) {
        Workbook wb = new HSSFWorkbook();
        try {
         Sheet sheet = wb.createSheet();
         Row r = sheet.createRow(0);
         List<ExcelHeader> headers = getHeaderList(clz);
         Collections.sort(headers);
         //寫標題
         for(int i=0;i<headers.size();i++) {
          r.createCell(i).setCellValue(headers.get(i).getTitle());
         }
         //寫數據
         Object obj = null;
         for(int i=0;i<objs.size();i++) {
          r = sheet.createRow(i+1);
          obj = objs.get(i);
          for(int j=0;j<headers.size();j++) {
           r.createCell(j).setCellValue(BeanUtils.getProperty(obj, getMethodName(headers.get(j))));
          }
         }
        } catch (IllegalAccessException e) {
         e.printStackTrace();
        } catch (InvocationTargetException e) {
         e.printStackTrace();
        } catch (NoSuchMethodException e) {
         e.printStackTrace();
        }
        return wb;
       }
       /**
        * 導出對象到Excel,不是基于模板的,直接新建一個Excel完成導出,基于路徑的導出
        * @param outPath 導出路徑
        * @param objs 對象列表
        * @param clz 對象類型
        */
       public void exportObj2Excel(String outPath,List objs,Class clz) {
        Workbook wb = handleObj2Excel(objs, clz);
        FileOutputStream fos = null;
        try {
         fos = new FileOutputStream(outPath);
         wb.write(fos);
        } catch (FileNotFoundException e) {
         e.printStackTrace();
        } catch (IOException e) {
         e.printStackTrace();
        } finally {
         try {
          if(fos!=null) fos.close();
         } catch (IOException e) {
          e.printStackTrace();
         }
        }
       }
       /**
        * 導出對象到Excel,不是基于模板的,直接新建一個Excel完成導出,基于流
        * @param os 輸出流
        * @param objs 對象列表
        * @param clz 對象類型
        */
       public void exportObj2Excel(OutputStream os,List objs,Class clz) {
        try {
         Workbook wb = handleObj2Excel(objs, clz);
         wb.write(os);
        } catch (IOException e) {
         e.printStackTrace();
        }
       }
       /**
        * 從類路徑讀取相應的Excel文件到對象列表
        * @param path 類路徑下的path
        * @param clz 對象類型
        * @param readLine 開始行,注意是標題所在行
        * @param tailLine 底部有多少行,在讀入對象時,會減去這些行
        * @return
        */
       public List<Object> readExcel2ObjsByClasspath(String path,Class clz,int readLine,int tailLine) {
        Workbook wb = null;
        try {
         wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
         return handlerExcel2Objs(wb, clz, readLine,tailLine);
        } catch (IOException e) {
         e.printStackTrace();
        }
        return null;
       }
       /**
        * 從文件路徑讀取相應的Excel文件到對象列表
        * @param path 文件路徑下的path
        * @param clz 對象類型
        * @param readLine 開始行,注意是標題所在行
        * @param tailLine 底部有多少行,在讀入對象時,會減去這些行
        * @return
        */
       public List<Object> readExcel2ObjsByPath(String path,Class clz,int readLine,int tailLine) {
        Workbook wb = null;
        try {
         wb = new HSSFWorkbook(TemplateFileUtil.getTemplates(path));
         return handlerExcel2Objs(wb, clz, readLine,tailLine);
        } catch (IOException e) {
         e.printStackTrace();
        }
        return null;
       }
       /**
        * 從類路徑讀取相應的Excel文件到對象列表,標題行為0,沒有尾行
        * @param path 路徑
        * @param clz 類型
        * @return 對象列表
        */
       public List<Object> readExcel2ObjsByClasspath(String path,Class clz) {
        return this.readExcel2ObjsByClasspath(path, clz, 0,0);
       }
       /**
        * 從文件路徑讀取相應的Excel文件到對象列表,標題行為0,沒有尾行
        * @param path 路徑
        * @param clz 類型
        * @return 對象列表
        */
       public List<Object> readExcel2ObjsByPath(String path,Class clz) {
        return this.readExcel2ObjsByPath(path, clz,0,0);
       }
       
       private String getCellValue(Cell c) {
        String o = null;
        switch (c.getCellType()) {
         case Cell.CELL_TYPE_BLANK:
          o = ""; break;
         case Cell.CELL_TYPE_BOOLEAN:
          o = String.valueOf(c.getBooleanCellValue()); break;
         case Cell.CELL_TYPE_FORMULA:
          o = String.valueOf(c.getCellFormula()); break;
         case Cell.CELL_TYPE_NUMERIC:
          o = String.valueOf(c.getNumericCellValue()); break;
         case Cell.CELL_TYPE_STRING:
          o = c.getStringCellValue(); break;
         default:
          o = null;
          break;
        }
        return o;
       }
       
       private List<Object> handlerExcel2Objs(Workbook wb,Class clz,int readLine,int tailLine) {
        Sheet sheet = wb.getSheetAt(0);
        List<Object> objs = null;
        try {
         Row row = sheet.getRow(readLine);
         objs = new ArrayList<Object>();
         Map<Integer,String> maps = getHeaderMap(row, clz);
         if(maps==null||maps.size()<=0) throw new RuntimeException("要讀取的Excel的格式不正確,檢查是否設定了合適的行");
         for(int i=readLine+1;i<=sheet.getLastRowNum()-tailLine;i++) {
          row = sheet.getRow(i);
          Object obj = clz.newInstance();
          for(Cell c:row) {
           int ci = c.getColumnIndex();
           String mn = maps.get(ci).substring(3);
           mn = mn.substring(0,1).toLowerCase()+mn.substring(1);
           BeanUtils.copyProperty(obj,mn, this.getCellValue(c));
          }
          objs.add(obj);
         }
        } catch (InstantiationException e) {
         e.printStackTrace();
        } catch (IllegalAccessException e) {
         e.printStackTrace();
        } catch (InvocationTargetException e) {
         e.printStackTrace();
        }
        return objs;
       }
       
       private List<ExcelHeader> getHeaderList(Class clz) {
        List<ExcelHeader> headers = new ArrayList<ExcelHeader>();
        Method[] ms = clz.getDeclaredMethods();
        for(Method m:ms) {
         String mn = m.getName();
         if(mn.startsWith("get")) {
          if(m.isAnnotationPresent(ExcelResources.class)) {
           ExcelResources er = m.getAnnotation(ExcelResources.class);
           headers.add(new ExcelHeader(er.title(),er.order(),mn));
          }
         }
        }
        return headers;
       }
       
       private Map<Integer,String> getHeaderMap(Row titleRow,Class clz) {
        List<ExcelHeader> headers = getHeaderList(clz);
        Map<Integer,String> maps = new HashMap<Integer, String>();
        for(Cell c:titleRow) {
         String id="codetool">

      Excel模板文件

      創建一個模板文件,如下圖:

      Springboot使用POI實現導出Excel文件示例

      POI導出Excel的模板文件

      測試類

      ?
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      23
      24
      25
      @SpringBootTest
      @RunWith(SpringRunner.class)
      public class ExportExcelTest {
       
       @Test
       public void test() throws Exception {
        List<WebDto> list = new ArrayList<WebDto>();
        list.add(new WebDto("知識林", "http://www.zslin.com", "admin", "111111", 555));
        list.add(new WebDto("權限系統", "http://basic.zslin.com", "admin", "111111", 111));
        list.add(new WebDto("校園網", "http://school.zslin.com", "admin", "222222", 333));
       
        Map<String, String> map = new HashMap<String, String>();
        map.put("title", "網站信息表");
        map.put("total", list.size()+" 條");
        map.put("date", getDate());
       
        ExcelUtil.getInstance().exportObj2ExcelByTemplate(map, "web-info-template.xls", new FileOutputStream("D:/temp/out.xls"),
          list, WebDto.class, true);
       }
       
       private String getDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        return sdf.format(new Date());
       }
      }

      執行測試方法后,查看D:/temp/out.xls文件后可以看到如下圖的內容:

      POI導出Excel結果圖

      Springboot使用POI實現導出Excel文件示例

      下載地址:Springboot.rar

      以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

      原文鏈接:http://blog.csdn.net/zsl129/article/details/52962074

      延伸 · 閱讀

      精彩推薦
      主站蜘蛛池模板: 国产精品香蕉一区二区三区 | 精品国产一区二区三区久久久狼 | 星空无限传媒xk8046 | 探花 在线 | 精品视频在线观看 | 男人天堂2023 | 日本中文字幕不卡在线一区二区 | 小sao货水好多真紧h的视频 | 99ri在线视频网 | 日本午夜vr影院新入口 | 香蕉精品高清在线观看视频 | 四虎影音先锋 | xxxxxx性受 | 日本xxxxx18护士xxx | 国产一区二区三区久久精品小说 | 热99精品 | 日本xxxxx高清免费观看 | 荷兰艾优apiyoo | 999精品视频这里只有精品 | 精品国产欧美精品v | 成人国产精品视频 | 日本精品vide·ssex日本 | 羞羞答答免费人成黄页在线观看国产 | 国产欧美一区二区三区精品 | 四虎影院在线免费观看 | 日本熟hdx | 色在线影院| 波多野结中文字幕在线69视频 | 啪啪无尽3d动漫漫画免费网站 | 日韩免费一区 | 婷婷久久热99在线精品 | 日韩二三区 | 穆挂英风流艳史小说 | 亚洲国产精品第一页 | 日不卡| 国产成人看片免费视频观看 | 日本日日黄| 爸爸的宝贝小说全文在线阅读 | 国产美女下面流出白浆视频 | 精品免费视在线视频观看 | 洗濯屋动漫在线观看 |