从数据库导出至excel的工具类

最近写了许多将数据从数据库导出至Excel的业务, 稍微整理个抽象类出来方便以后复用或拓展

只支持导出到只有一个sheet的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
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.util.List;

/**
* Excel Sheet 导出工具
*
* @author Tomoto
* @version 1.0 2022/7/14 10:51
* @since 1.0
*/
public abstract class ExcelSheetExportHelper<T> {

private Sheet sheet;

/**
* 获取表头
*
* @return 表头
*/
public abstract String[] getHeader();

/**
* 获取文件名
*
* @return 文件名
*/
public abstract String getFilename();

/**
* 填充行数据
*
* @param vo vo
* @param row 行
* @param index 行索引
*/
public abstract void fillRowData(T vo, Row row, int index);

/**
* 初始化
* <p>
* 设置表头格式, 填充表头
*
* @return workbook
*/
public Workbook init() {
Workbook workbook = new SXSSFWorkbook();
sheet = workbook.createSheet(getFilename());

// 设置风格
sheet.autoSizeColumn(1, true);
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); // 左边框
cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); // 上边框
cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); // 右边框

// 设置表头
Row row = sheet.createRow(0);
for (int i = 0; i < getHeader().length; i++) {
Cell hCell = row.createCell(i);
hCell.setCellStyle(cellStyle);
hCell.setCellValue(getHeader()[i]);
}
return workbook;
}

/**
* 导出数据
*
* @param voList vo数组
* @param index 起始index
*/
public void exportData(List<T> voList, int index) {
for (T vo : voList) {
index++;
fillRowData(vo, sheet.createRow(index), index);
}
}

}