陶杰
2024-08-22 ee9032d9baf5f33e376d2d2699136e0a7b26bec7
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
package com.mzl.flower.utils;
 
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
 
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
public class ExcelExportUtil {
    //显示的导出表的标题
    private String title;
    //导出表的列名
    private String[] rowName ;
 
    private List<HeadRow> headRows;
 
    private List<Object[]> dataList = new ArrayList<>();
 
    private HttpServletResponse response;
 
    //默认日期格式
    private String dateFormat = "yyyy-MM-dd";
 
    public static class HeadRow{
        int rowIndex;
        List<HeadColumn> columns;
 
        public HeadRow(int rowIndex, List<HeadColumn> columns){
            this.columns = columns;
            this.rowIndex = rowIndex;
        }
    }
 
    public static class HeadColumn{
        int columnIndex;
        int rowspan;
        int colspan;
        String name;
 
        public HeadColumn(int columnIndex, int rowspan, int colspan, String name){
            this.columnIndex = columnIndex;
            this.rowspan = rowspan;
            this.colspan = colspan;
            this.name = name;
        }
    }
 
    public ExcelExportUtil(String title, List<HeadRow> headRows, List<Object[]> dataList, HttpServletResponse response){
        this.dataList = dataList;
        this.headRows = headRows;
        this.title = title;
        this.response = response;
    }
 
    public ExcelExportUtil(String title, List<HeadRow> headRows, List<Object[]> dataList, HttpServletResponse response, String dateFormat){
        this.dataList = dataList;
        this.headRows = headRows;
        this.title = title;
        this.response = response;
        this.dateFormat = dateFormat;
    }
 
    /**
     * 构造函数,传入要导出的数据
     * @param title  标题
     * @param rowName  列名
     * @param dataList 数据集合 List
     * @param response http响应
     */
    public ExcelExportUtil(String title, String[] rowName, List<Object[]> dataList, HttpServletResponse response){
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
        this.response = response;
    }
 
    /**
     * 构造函数,传入要导出的数据,带日期格式
     * @param title  标题
     * @param rowName  列名
     * @param dataList 数据集合 List
     * @param response http响应
     * @param dateFormat 日期格式
     */
    public ExcelExportUtil(String title, String[] rowName, List<Object[]> dataList, HttpServletResponse response, String dateFormat){
        this.dataList = dataList;
        this.rowName = rowName;
        this.title = title;
        this.response = response;
        this.dateFormat = dateFormat;
    }
 
    private int prepareHeader(HSSFSheet sheet, HSSFCellStyle columnTopStyle){
        int step = 0;
        if(headRows != null){
            for(HeadRow row : headRows){
                int firstRow = row.rowIndex;
                HSSFRow rowHeader = sheet.getRow(firstRow);
                if(rowHeader == null){
                    rowHeader = sheet.createRow(firstRow);
                }
                List<HeadColumn> columns = row.columns;
                int s = 1;
                for(HeadColumn c : columns){
                    int lastRow = firstRow + c.rowspan - 1;
                    int firstCol = c.columnIndex;
                    int lastCol = firstCol + c.colspan - 1;
                    if(lastRow > firstRow || lastCol > firstCol) {
                        for(int i = firstRow; i <= lastRow; i++){
                            for(int j = firstCol; j <= lastCol; j++){
                                HSSFRow rowHeader1 = sheet.getRow(i);
                                if(rowHeader1 == null){
                                    rowHeader1 = sheet.createRow(i);
                                }
                                HSSFCell cell = rowHeader1.getCell(j);
                                if(cell == null){
                                    cell = rowHeader1.createCell(j);
                                }
                                cell.setCellStyle(columnTopStyle);
                            }
                        }
                        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, firstCol, lastCol));
                    }
 
                    HSSFCell cell = rowHeader.getCell(firstCol);
                    if(cell == null){
                        cell = rowHeader.createCell(firstCol);
                    }
 
                    cell.setCellStyle(columnTopStyle);
                    cell.setCellType(CellType.STRING);
                    HSSFRichTextString text = new HSSFRichTextString(c.name);
                    cell.setCellValue(text);
 
                    if(s < c.rowspan){
                        s = c.rowspan;
                    }
                }
                step += s;
            }
        }else if(rowName != null){
            // 产生表格标题行
            HSSFRow rowTitle = sheet.createRow(0);
            HSSFCell cellTitle = rowTitle.createCell(0);
 
            sheet.addMergedRegion(new CellRangeAddress(0, 1, 0, (rowName.length-1)));
            cellTitle.setCellStyle(columnTopStyle);
            cellTitle.setCellValue(title);
 
            // 定义所需列数
            int columnNum = rowName.length;
            HSSFRow rowRowName = sheet.createRow(2);                // 在索引2的位置创建行(最顶端的行开始的第二行)
 
            // 将列头设置到sheet的单元格中
            for(int n = 0; n < columnNum; n++){
                HSSFCell cellRowName = rowRowName.createCell(n);               //创建列头对应个数的单元格
                cellRowName.setCellType(CellType.STRING);             //设置列头单元格的数据类型
                HSSFRichTextString text = new HSSFRichTextString(rowName[n]);
                cellRowName.setCellValue(text);                                 //设置列头单元格的值
                cellRowName.setCellStyle(columnTopStyle);                       //设置列头单元格样式
            }
 
            step = 3;
        }
 
        return step;
    }
 
    /*
     * 导出数据
     * */
    public void export() throws Exception{
        try{
            HSSFWorkbook workbook = new HSSFWorkbook();                     // 创建工作簿对象
            HSSFSheet sheet = workbook.createSheet(title);                  // 创建工作表
 
            //sheet样式定义【getColumnTopStyle()/getStyle()均为自定义方法 - 在下面  - 可扩展】
            HSSFCellStyle columnTopStyle = this.getColumnTopStyle(workbook);//获取列头样式对象
            HSSFCellStyle style = this.getStyle(workbook);                  //单元格样式对象
 
            int step = prepareHeader(sheet, columnTopStyle);
 
            //将查询出的数据设置到sheet对应的单元格中
            if (null != dataList && dataList.size() > 0) {
                int cellNum = 0;
 
                for(int i = 0; i < dataList.size(); i++){
                    Object[] obj = dataList.get(i);//遍历每个对象
                    HSSFRow row = sheet.createRow(i + step);//创建所需的行数
 
                    for(int j = 0; j < obj.length; j++){
                        HSSFCell cell = row.createCell(j);   //设置单元格的数据类型
                        //HSSFCell  cell = row.createCell(j,HSSFCell.CELL_TYPE_STRING);   //设置单元格的数据类型
 
                        cell.setCellStyle(style);                                   //设置单元格样式
 
                        cellNum = setCellValue(cell, obj[j], cellNum, row);
                        cellNum++;
                    }
                }
            }
 
            if(workbook !=null){
                OutputStream out = null;
                try{
                    String fileName = "Excel-" + String.valueOf(System.currentTimeMillis()).substring(4, 13) + ".xls";
                    String headStr = "attachment; filename=\"" + fileName + "\"";
                    response.setContentType("application/vnd.ms-excel");
                    response.setHeader("Content-Disposition", headStr);
                    response.addHeader("filename", URLEncoder.encode(fileName, "UTF-8"));
                    out = response.getOutputStream();
                    workbook.write(out);
                    out.flush();
                }
                catch (IOException e){
                }
                finally{
                    if (null != out){
                        out.close();
                    }
                }
            }
 
        }catch(Exception e){
            e.printStackTrace();
        }
 
    }
 
    private int setCellValue(HSSFCell cell, Object value, int cellNum, HSSFRow row){
        String textValue = null;
        if (value instanceof Integer) {
            int intValue = (Integer) value;
            cell.setCellValue(intValue);
        } else if (value instanceof Float) {
            float fValue = (Float) value;
            cell.setCellValue(fValue);
        } else if (value instanceof Double) {
            double dValue = (Double) value;
            cell.setCellValue(dValue);
        } else if (value instanceof Long) {
            long longValue = (Long) value;
            cell.setCellValue(longValue);
        } else if (value instanceof Boolean) {
            boolean bValue = (Boolean) value;
            cell.setCellValue(bValue);
        } else if (value instanceof Date) {
            Date date = (Date) value;
            SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
            textValue = sdf.format(date);
        } else if (value instanceof ZonedDateTime){
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(dateFormat);
            textValue = dateTimeFormatter.format((ZonedDateTime) value);
        }else if (value instanceof String[]) {
            String[] strArr = (String[]) value;
            for (int j = 0; j < strArr.length; j++) {
                String str = strArr[j];
                cell.setCellValue(str);
                if (j != strArr.length - 1) {
                    cellNum++;
                    cell = row.createCell(cellNum);
                }
            }
        } else if (value instanceof Double[]) {
            Double[] douArr = (Double[]) value;
            for (int j = 0; j < douArr.length; j++) {
                Double val = douArr[j];
                // 值不为空则set Value
                if (val != null) {
                    cell.setCellValue(val);
                }
 
                if (j != douArr.length - 1) {
                    cellNum++;
                    cell = row.createCell(cellNum);
                }
            }
        } else {
            // 其它数据类型都当作字符串简单处理
            String empty = "";
            textValue = value == null ? empty : value.toString();
        }
        if (textValue != null) {
            HSSFRichTextString richString = new HSSFRichTextString(textValue);
            cell.setCellValue(richString);
        }
        return cellNum;
    }
 
    /*
     * 列头单元格样式
     */
    private HSSFCellStyle getColumnTopStyle(HSSFWorkbook workbook) {
 
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        font.setFontHeightInPoints((short)11);
        //字体加粗
        font.setBold(true);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(false);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
 
        return style;
 
    }
 
    /*
     * 列数据信息单元格样式
     */
    private HSSFCellStyle getStyle(HSSFWorkbook workbook) {
        // 设置字体
        HSSFFont font = workbook.createFont();
        //设置字体大小
        //font.setFontHeightInPoints((short)10);
        //字体加粗
        //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        //设置字体名字
        font.setFontName("Courier New");
        //设置样式;
        HSSFCellStyle style = workbook.createCellStyle();
        //设置底边框;
        style.setBorderBottom(BorderStyle.THIN);
        //设置底边框颜色;
        style.setBottomBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置左边框;
        style.setBorderLeft(BorderStyle.THIN);
        //设置左边框颜色;
        style.setLeftBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置右边框;
        style.setBorderRight(BorderStyle.THIN);
        //设置右边框颜色;
        style.setRightBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //设置顶边框;
        style.setBorderTop(BorderStyle.THIN);
        //设置顶边框颜色;
        style.setTopBorderColor(HSSFColor.HSSFColorPredefined.BLACK.getIndex());
        //在样式用应用设置的字体;
        style.setFont(font);
        //设置自动换行;
        style.setWrapText(true);
        //设置水平对齐的样式为居中对齐;
        style.setAlignment(HorizontalAlignment.CENTER);
        //设置垂直对齐的样式为居中对齐;
        style.setVerticalAlignment(VerticalAlignment.CENTER);
 
        return style;
 
    }
}