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

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

PHP教程|ASP.NET教程|JAVA教程|ASP教程|編程技術|正則表達式|C/C++|

服務器之家 - 編程語言 - JAVA教程 - 基于apache poi根據模板導出excel的實現方法

基于apache poi根據模板導出excel的實現方法

2020-11-06 21:17Java教程網 JAVA教程

下面小編就為大家帶來一篇基于apache poi根據模板導出excel的實現方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

需要預先新建編輯好一個excel文件,設置好樣式。

編輯好輸出的數據,根據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
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package com.icourt.util;
 
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
 
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
/**
 * 描述:poi根據模板導出excel,根據excel坐標賦值,如(B1)
 */
public class ExcelExportUtil {
 
  //模板map
  private Map<String, Workbook> tempWorkbook = new HashMap<String, Workbook>();
  //模板輸入流map
  private Map<String, InputStream> tempStream = new HashMap<String, InputStream>();
 
  /**
   * 功能:按模板向Excel中相應地方填充數據
   */
  public void writeData(String templateFilePath, Map<String, Object> dataMap, int sheetNo) throws IOException, InvalidFormatException {
    if (dataMap == null || dataMap.isEmpty()) {
      return;
    }
    //讀取模板
    Workbook wbModule = getTempWorkbook(templateFilePath);
    //數據填充的sheet
    Sheet wsheet = wbModule.getSheetAt(sheetNo);
 
    for (Entry<String, Object> entry : dataMap.entrySet()) {
      String point = entry.getKey();
      Object data = entry.getValue();
 
      TempCell cell = getCell(point, data, wsheet);
      //指定坐標賦值
      setCell(cell, wsheet);
    }
 
    //設置生成excel中公式自動計算
    wsheet.setForceFormulaRecalculation(true);
  }
 
  /**
   * 功能:按模板向Excel中列表填充數據.只支持列合并
   */
  public void writeDateList(String templateFilePath, String[] heads, List<Map<Integer, Object>> datalist, int sheetNo) throws IOException, InvalidFormatException {
    if (heads == null || heads.length <= 0 || CollectionUtils.isEmpty(datalist)) {
      return;
    }
    //讀取模板
    Workbook wbModule = getTempWorkbook(templateFilePath);
    //數據填充的sheet
    Sheet wsheet = wbModule.getSheetAt(sheetNo);
 
    //列表數據模板cell
    List<TempCell> tempCells = new ArrayList<TempCell>(heads.length);
    for (String point : heads) {
      TempCell tempCell = getCell(point, null, wsheet);
      //取得合并單元格位置 -1:表示不是合并單元格
      int pos = isMergedRegion(wsheet, tempCell.getRow(), tempCell.getColumn());
      if (pos > -1) {
        CellRangeAddress range = wsheet.getMergedRegion(pos);
        tempCell.setColumnSize(range.getLastColumn() - range.getFirstColumn());
      }
      tempCells.add(tempCell);
    }
    //賦值
    for (int i = 0; i < datalist.size(); i++) {//數據行
      Map<Integer, Object> dataMap = datalist.get(i);
      for (int j = 0; j < tempCells.size(); j++) {//列
        TempCell tempCell = tempCells.get(j);
        tempCell.setData(dataMap.get(j + 1));
        setCell(tempCell, wsheet);
        tempCell.setRow(tempCell.getRow() + 1);
      }
    }
  }
 
  /**
   * 功能:獲取輸入工作區
   */
  private Workbook getTempWorkbook(String templateFilePath) throws IOException, InvalidFormatException {
    if (!tempWorkbook.containsKey(templateFilePath)) {
      InputStream inputStream = getInputStream(templateFilePath);
      tempWorkbook.put(templateFilePath, WorkbookFactory.create(inputStream));
    }
    return tempWorkbook.get(templateFilePath);
  }
 
  /**
   * 功能:獲得模板輸入流
   */
  private InputStream getInputStream(String templateFilePath) throws FileNotFoundException {
    if (!tempStream.containsKey(templateFilePath)) {
      tempStream.put(templateFilePath, new FileInputStream((templateFilePath)));
    }
    return tempStream.get(templateFilePath);
  }
 
  /**
   * 功能:獲取單元格數據,樣式(根據坐標:B3)
   */
  private TempCell getCell(String point, Object data, Sheet sheet) {
    TempCell tempCell = new TempCell();
 
    //得到列  字母
    String lineStr = "";
    String reg = "[A-Z]+";
    Pattern p = Pattern.compile(reg);
    Matcher m = p.matcher(point);
    while (m.find()) {
      lineStr = m.group();
    }
    //將列字母轉成列號 根據ascii轉換
    char[] ch = lineStr.toCharArray();
    int column = 0;
    for (int i = 0; i < ch.length; i++) {
      char c = ch[i];
      int post = ch.length - i - 1;
      int r = (int) Math.pow(10, post);
      column = column + r * ((int) c - 65);
    }
    tempCell.setColumn(column);
 
    //得到行號
    reg = "[1-9]+";
    p = Pattern.compile(reg);
    m = p.matcher(point);
    while (m.find()) {
      tempCell.setRow((Integer.parseInt(m.group()) - 1));
    }
 
    //獲取模板指定單元格樣式,設置到tempCell(寫列表數據的時候用)
    Row rowIn = sheet.getRow(tempCell.getRow());
    if (rowIn == null) {
      rowIn = sheet.createRow(tempCell.getRow());
    }
    Cell cellIn = rowIn.getCell(tempCell.getColumn());
    if (cellIn == null) {
      cellIn = rowIn.createCell(tempCell.getColumn());
    }
    tempCell.setCellStyle(cellIn.getCellStyle());
    tempCell.setData(data);
    return tempCell;
  }
 
  /**
   * 功能:給指定坐標單元格賦值
   */
  private void setCell(TempCell tempCell, Sheet sheet) {
    if (tempCell.getColumnSize() > -1) {
      CellRangeAddress rangeAddress = mergeRegion(sheet, tempCell.getRow(), tempCell.getRow(), tempCell.getColumn(), tempCell.getColumn() + tempCell.getColumnSize());
      setRegionStyle(tempCell.getCellStyle(), rangeAddress, sheet);
    }
 
    Row rowIn = sheet.getRow(tempCell.getRow());
    if (rowIn == null) {
      copyRows(tempCell.getRow() - 1, tempCell.getRow() - 1, tempCell.getRow(), sheet);//復制上一行
      rowIn = sheet.getRow(tempCell.getRow());
    }
    Cell cellIn = rowIn.getCell(tempCell.getColumn());
    if (cellIn == null) {
      cellIn = rowIn.createCell(tempCell.getColumn());
    }
    //根據data類型給cell賦值
    if (tempCell.getData() instanceof String) {
      cellIn.setCellValue((String) tempCell.getData());
    } else if (tempCell.getData() instanceof Integer) {
      cellIn.setCellValue((int) tempCell.getData());
    } else if (tempCell.getData() instanceof Double) {
      cellIn.setCellValue((double) tempCell.getData());
    } else {
      cellIn.setCellValue((String) tempCell.getData());
    }
    //樣式
    if (tempCell.getCellStyle() != null && tempCell.getColumnSize() == -1) {
      cellIn.setCellStyle(tempCell.getCellStyle());
    }
  }
 
  /**
   * 功能:寫到輸出流并移除資源
   */
  public void writeAndClose(String templateFilePath, OutputStream os) throws IOException, InvalidFormatException {
    if (getTempWorkbook(templateFilePath) != null) {
      getTempWorkbook(templateFilePath).write(os);
      tempWorkbook.remove(templateFilePath);
    }
    if (getInputStream(templateFilePath) != null) {
      getInputStream(templateFilePath).close();
      tempStream.remove(templateFilePath);
    }
  }
 
  /**
   * 功能:判斷指定的單元格是否是合并單元格
   */
  private Integer isMergedRegion(Sheet sheet, int row, int column) {
    for (int i = 0; i < sheet.getNumMergedRegions(); i++) {
      CellRangeAddress range = sheet.getMergedRegion(i);
      int firstColumn = range.getFirstColumn();
      int lastColumn = range.getLastColumn();
      int firstRow = range.getFirstRow();
      int lastRow = range.getLastRow();
      if (row >= firstRow && row <= lastRow) {
        if (column >= firstColumn && column <= lastColumn) {
          return i;
        }
      }
    }
    return -1;
  }
 
  /**
   * 功能:合并單元格
   */
  private CellRangeAddress mergeRegion(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) {
    CellRangeAddress rang = new CellRangeAddress(firstRow, lastRow, firstCol, lastCol);
    sheet.addMergedRegion(rang);
    return rang;
  }
 
  /**
   * 功能:設置合并單元格樣式
   */
  private void setRegionStyle(CellStyle cs, CellRangeAddress region, Sheet sheet) {
    for (int i = region.getFirstRow(); i <= region.getLastRow(); i++) {
      Row row = sheet.getRow(i);
      if (row == null) row = sheet.createRow(i);
      for (int j = region.getFirstColumn(); j <= region.getLastColumn(); j++) {
        Cell cell = row.getCell(j);
        if (cell == null) {
          cell = row.createCell(j);
          cell.setCellValue("");
        }
        cell.setCellStyle(cs);
      }
    }
  }
 
  /**
   * 功能:copy rows
   */
  private void copyRows(int startRow, int endRow, int pPosition, Sheet sheet) {
    int pStartRow = startRow - 1;
    int pEndRow = endRow - 1;
    int targetRowFrom;
    int targetRowTo;
    int columnCount;
    CellRangeAddress region = null;
    int i;
    int j;
    if (pStartRow == -1 || pEndRow == -1) {
      return;
    }
    // 拷貝合并的單元格
    for (i = 0; i < sheet.getNumMergedRegions(); i++) {
      region = sheet.getMergedRegion(i);
      if ((region.getFirstRow() >= pStartRow)
          && (region.getLastRow() <= pEndRow)) {
        targetRowFrom = region.getFirstRow() - pStartRow + pPosition;
        targetRowTo = region.getLastRow() - pStartRow + pPosition;
        CellRangeAddress newRegion = region.copy();
        newRegion.setFirstRow(targetRowFrom);
        newRegion.setFirstColumn(region.getFirstColumn());
        newRegion.setLastRow(targetRowTo);
        newRegion.setLastColumn(region.getLastColumn());
        sheet.addMergedRegion(newRegion);
      }
    }
    // 設置列寬
    for (i = pStartRow; i <= pEndRow; i++) {
      Row sourceRow = sheet.getRow(i);
      columnCount = sourceRow.getLastCellNum();
      if (sourceRow != null) {
        Row newRow = sheet.createRow(pPosition - pStartRow + i);
        newRow.setHeight(sourceRow.getHeight());
        for (j = 0; j < columnCount; j++) {
          Cell templateCell = sourceRow.getCell(j);
          if (templateCell != null) {
            Cell newCell = newRow.createCell(j);
            copyCell(templateCell, newCell);
          }
        }
      }
    }
  }
 
  /**
   * 功能:copy cell,不copy值
   */
  private void copyCell(Cell srcCell, Cell distCell) {
    distCell.setCellStyle(srcCell.getCellStyle());
    if (srcCell.getCellComment() != null) {
      distCell.setCellComment(srcCell.getCellComment());
    }
    int srcCellType = srcCell.getCellType();
    distCell.setCellType(srcCellType);
  }
 
  /**
   * 描述:臨時單元格數據
   */
  class TempCell {
    private int row;
    private int column;
    private CellStyle cellStyle;
    private Object data;
    //用于列表合并,表示幾列合并
    private int columnSize = -1;
 
    public int getColumn() {
      return column;
    }
 
    public void setColumn(int column) {
      this.column = column;
    }
 
    public int getRow() {
      return row;
    }
 
    public void setRow(int row) {
      this.row = row;
    }
 
    public CellStyle getCellStyle() {
      return cellStyle;
    }
 
    public void setCellStyle(CellStyle cellStyle) {
      this.cellStyle = cellStyle;
    }
 
    public Object getData() {
      return data;
    }
 
    public void setData(Object data) {
      this.data = data;
    }
 
    public int getColumnSize() {
      return columnSize;
    }
 
    public void setColumnSize(int columnSize) {
      this.columnSize = columnSize;
    }
  }
 
  public static void main(String[] args) throws FileNotFoundException, IOException, InvalidFormatException {
    String templateFilePath = ExcelExportUtil.class.getClassLoader().getResource("plugin/ProTiming.xlsx").getPath();
    File file = new File("/Users/sql/Downloads/test/data.xlsx");
    OutputStream os = new FileOutputStream(file);
 
    ExcelExportUtil excel = new ExcelExportUtil();
    Map<String, Object> dataMap = new HashMap<String, Object>();
    dataMap.put("B1", "03_Alpha_項目工作時間統計表");
    dataMap.put("B2", "統計時間:2017/01/01 - 2017/03/31");
 
    excel.writeData(templateFilePath, dataMap, 0);
 
    List<Map<Integer, Object>> datalist = new ArrayList<Map<Integer, Object>>();
    Map<Integer, Object> data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
 
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
 
    data = new HashMap<Integer, Object>();
    data.put(1, "3/10/17");
    data.put(2, "18:50");
    data.put(3, "19:00");
    data.put(4, "李子鵬");
    data.put(5, "新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用新增項目鍵值對接口,供任務計時調用");
    data.put(6, "代碼開發");
    data.put(7, "3.17");
    datalist.add(data);
    data = new HashMap<Integer, Object>();
    data.put(1, "");
    data.put(2, "");
    data.put(3, "");
    data.put(4, "");
    data.put(5, "");
    data.put(6, "");
    data.put(7, "");
    datalist.add(data);
 
    String[] heads = new String[]{"B4", "C4", "D4", "E4", "F4", "G4", "H4"};
    excel.writeDateList(templateFilePath, heads, datalist, 0);
 
    //寫到輸出流并移除資源
    excel.writeAndClose(templateFilePath, os);
 
    os.flush();
    os.close();
  }
 
}

大體思路:

最主要是制作好模版

代碼根據模版,讀取設置好的列的格式,在循環數據行,讀取模版中的對應的行,存在該行就取得,不存在看是否需要copy某一行,不需要就手動創建無制定格式的行,后面在為該行的每一列對應的給個單元格制定格式和數據。

以上這篇基于apache poi根據模板導出excel的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 欧美日韩亚洲另类人人澡 | 91tv在线 | 欧美视频黑鬼大战白妞 | 校园全肉高h湿一女多男 | 国产福利一区二区三区四区 | 日本欧美强乱视频在线 | 万域之王动漫在线观看全集免费播放 | 国产高清视频一区二区 | 婷婷九月 | 97se亚洲国产综合自在线观看 | 亚洲男1069gay男猛男 | 日本中文字幕在线观看视频 | 久久最新地址获取 | 日韩亚洲欧美理论片 | 91国内精品久久久久影院优播 | 国语自产拍在线观看7m | 国内精品久久久久影院男同志 | 久久中文字幕综合不卡一二区 | 11 13加污女qq看他下面 | 久久亚洲精品AV无码四区 | 午夜福到在线4国产 | 狠狠色狠狠色综合婷婷tag | 91视频破解 | 狠狠狠地啪香蕉 | 女同学高中你下面好紧 | 国产91精品久久久久久久 | 欧美在线一级片 | 色婷婷六月丁香在线观看 | 小草观看免费高清视频 | jazz中国女人护士 | 91热爆在线 | 男男按摩1069gⅴ | 成年人在线视频免费观看 | 精品视频在线免费看 | 成人精品一区二区三区 | 成人毛片高清视频观看 | 色先锋av资源中文字幕 | 草莓绿巨人香蕉茄子芭乐 | 婷婷99av综合| 深夜福利影院 | 四虎影院免费在线 |