zhuguifei
2026-03-10 2c1fd10c6fbabb8e9f0e9f07fe66fb36c008e883
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
479
480
481
482
483
484
485
486
package com.shlanbao.tzsc.utils.excel;
 
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
 
import com.shlanbao.tzsc.utils.tools.MathUtil;
 
 
public class ExportExcel {
    private short encoding = HSSFWorkbook.ENCODING_UTF_16;
    private int cellType = HSSFCell.CELL_TYPE_STRING;
    public ExportExcel() {
    }
    /**
     * @param args
     */
    public static void main(String[] args)  throws IOException {
        ExportExcel ee = new ExportExcel(); 
        FileOutputStream fos;
 
    }
    /**
     * 报表导出excel格式
     * @param thTables    th表头表格         EG:int[] thTables={1,3,13};当前开始行,当前结束行,一共多少列
     * @param ths        th表格对应的内容  EG:th.add("1,1,1,3,跨行1");第1行;第1列开始 ~ 第1列结束  一共 跨3行
     * @param tdTables    td表格        EG:int[] tdTables={4,(4+list条数-1),13}; 当前开始行,当前结束行,一共多少列
     * @param tdVals    td表格对应的内容 EG:maps.put((4+i)+",1,1,1","项目1");//第N行;第H列开始 ~ 第H列结束 一共 跨S行
     * @return
     */
    public HSSFWorkbook exportExcel(int[] thTables, List<String> ths,
            int[] tdTables, List<Map<String,String>> tdVals) {
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet();
        workBook.setSheetName(0, "temp1", encoding);
        sheet.setVerticallyCenter(true);
        sheet.setDefaultColumnWidth((short) 10);
        HSSFCellStyle tableStyle = getTableStyle(workBook,true);
        HSSFCellStyle tdStyle = getTableStyle(workBook,false);
        if(null!=thTables){//th表格
            //当前开始行,当前结束行,一共多少列
            createRow((thTables[0]-1), thTables[1],thTables[2],tableStyle,sheet);
        }
        if(null!=ths){//th跨行跨列,合并单元格
            for(String str:ths){
                String[] args = str.split(",");
                //第0行 第0列开始 ;跨2行 到 第0列结束
                mergedRegion(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1,
                        Integer.parseInt(args[3]) - 1,
                        Integer.parseInt(args[2]) - 1, sheet);// 合并单元格
                setValue(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1, 
                        args[4], 
                        tableStyle,cellType, sheet);
            }
        }
        int startLine=7;
        for(int i=0;i<100;i++){
            HSSFRow row = sheet.createRow(startLine++);
            try {
                for(int j=0;j<10;j++){
                    HSSFCell cell=row.createCell((short) j);
                    cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                    cell.setCellValue("测试");
                    
                }
                
                
            } catch (Exception e) {
                e.printStackTrace();
            } 
        }
        return workBook;
    }
 
    /**
     * 报表导出excel格式
     * @param thTables    th表头表格         EG:int[] thTables={1,3,13};当前开始行,当前结束行,一共多少列
     * @param ths        th表格对应的内容  EG:th.add("1,1,1,3,跨行1");第1行;第1列开始 ~ 第1列结束  一共 跨3行
     * @param tdTables    td表格        EG:int[] tdTables={4,(4+list条数-1),13}; 当前开始行,当前结束行,一共多少列
     * @param tdVals    td表格对应的内容 EG:maps.put((4+i)+",1,1,1","项目1");//第N行;第H列开始 ~ 第H列结束 一共 跨S行
     * @return
     */
    public HSSFWorkbook exportExcel(int[] thTables, List<String> ths,int startLine,String[] method,Class clazz,List<?> list) {
        HSSFWorkbook workBook = new HSSFWorkbook();
        HSSFSheet sheet = workBook.createSheet();
        workBook.setSheetName(0, "temp1", encoding);
        sheet.setVerticallyCenter(true);
        sheet.setDefaultColumnWidth((short) 24);
        HSSFCellStyle tableStyle = getTableStyle(workBook,true);
        HSSFCellStyle tdStyle = getTableStyle(workBook,false);
        if(null!=thTables){//th表格
            //当前开始行,当前结束行,一共多少列
            createRow((thTables[0]-1), thTables[1],thTables[2],tableStyle,sheet);
        }
        if(null!=ths){//th跨行跨列,合并单元格
            for(String str:ths){
                String[] args = str.split(",");
                //第0行 第0列开始 ;跨2行 到 第0列结束
                mergedRegion(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1,
                        Integer.parseInt(args[3]) - 1,
                        Integer.parseInt(args[2]) - 1, sheet);// 合并单元格
                setValue(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1, 
                        args[4], 
                        tableStyle,cellType, sheet);
            }
        }
        
        for(Object o:list){
            HSSFRow row = sheet.createRow(startLine++);
            BigDecimal v=null;
            BigDecimal v2=null;
            Integer index=null;
            Object value=null;
            for(int i=0;i<method.length;i++){
                Method m;
                try {
                    m = clazz.getDeclaredMethod(method[i]);
                    Type rType=m.getGenericReturnType();
                    if(rType==Double.TYPE || rType==Float.TYPE){
                        value=m.invoke(o);
                        if(value!=null){
                            value=MathUtil.roundHalfUp((Double) value, 2);
                        }else{
                            value="0.0";
                        }
                    }else if(rType==Integer.TYPE || rType==Long.TYPE ||rType==Short.TYPE){
                        value= m.invoke(o)!=null?m.invoke(o).toString():"0";
                    }else{
                        value= m.invoke(o)!=null?m.invoke(o).toString().trim():"";
                        try {
                            if(!value.equals("")){
                                v=new BigDecimal(value.toString());
                                Integer stat=v.compareTo(new BigDecimal(1000000000));
                                if(stat>=1){
                                    //存在大数字原样输出
                                }else{
                                    value=(v.setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
                                    index=value.toString().indexOf('.');
                                    String d=value.toString().substring(index, value.toString().length());
                                    double ys=Double.parseDouble(d);
                                    if(ys==0){
                                        value=value.toString().substring(0, index);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            //e.printStackTrace();
                        }
                    }
                    HSSFCell cell=row.createCell((short) i);
                    cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                    cell.setCellValue(value.toString());
                    if (tdStyle != null) {
                        cell.setCellStyle(tdStyle);
                    }
                    
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        }
        return workBook;
    }
    /**
     * 表格样式
     * 
     * @return
     */
    public HSSFCellStyle getTableStyle(HSSFWorkbook workBook,boolean isBgGround) {
        HSSFCellStyle style = workBook.createCellStyle();
        HSSFFont font = workBook.createFont();
        font.setFontName("Arial");
        font.setFontHeightInPoints((short) 12);// 设置字体大小
        font.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上线居中
//        if(isBgGround){
//            style.setFillForegroundColor((short) 22);//背景颜色
//            style.setFillBackgroundColor((short) 22);//背景颜色
//            style.setFillPattern(HSSFCellStyle.SPARSE_DOTS);//背景颜色
//        }
        style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        style.setBorderRight(HSSFCellStyle.BORDER_THIN);
        style.setBorderTop(HSSFCellStyle.BORDER_THIN);
        style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        style.setWrapText(true);
        style.setFont(font);
        return style;
    }
 
    /**
     * 创建一行
     * @param currentRow
     * @param rowNum
     * @param colNum
     * @param style
     * @param sheet
     */
    public void createRow(int currentRow, int rowNum, int colNum,
            HSSFCellStyle style,HSSFSheet sheet) {
        for (int rowIndex = currentRow; rowIndex < rowNum; rowIndex++) {
            HSSFRow row = sheet.createRow(rowIndex);
            for (short cellIndex = 0; cellIndex < colNum; cellIndex++) {
                HSSFCell cell = row.createCell(cellIndex);
                cell.setEncoding(encoding);
                if (style != null) {
                    cell.setCellStyle(style);
                }
                cell.setCellType(cellType);
                cell.setCellValue("");
            }
        }
    }
    /**
     * 设置冻结列
     * @param rowFrom
     * @param colFrom
     * @param rowTo
     * @param colTo
     * @param sheet
     */
    public void mergedRegion(int rowFrom, int colFrom, int rowTo, int colTo,HSSFSheet sheet) {
        Region region = new Region(rowFrom, (short) colFrom, rowTo, (short) colTo);
        sheet.addMergedRegion(region);
    }
    /**
     * 设置值
     * @param rowIndex
     * @param colIndex
     * @param value
     * @param style
     * @param type
     * @param sheet
     */
    public void setValue(int rowIndex, int colIndex, String value,
            HSSFCellStyle style, int type,HSSFSheet sheet) {
        HSSFRow row = sheet.getRow(rowIndex);
        HSSFCell cell = row.getCell((short) colIndex);
        cell.setCellType(type);
        if (style != null) {
            cell.setCellStyle(style);
        }
        cell.setCellValue(value);
    }
    
    /**
     * 写出
     * @param workBook
     * @param path
     */
    public void write(HSSFWorkbook workBook, String path) {
 
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(path);
            workBook.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 分sheet的excel导出
     * @param thTables
     * @param ths
     * @param tdTables
     * @param tdVals
     * @return
     */
    public HSSFWorkbook exportExcel2(int[] thTables, List<String> ths,
            int[] tdTables, List<List<Map<String,String>>> tdValss) {
        HSSFWorkbook workBook = new HSSFWorkbook();
        for (int k = 0; k < tdValss.size(); k++) {
        List<Map<String,String>> tdVals=tdValss.get(k);
        HSSFSheet sheet = workBook.createSheet();
        workBook.setSheetName(k, "sheet"+(k+1), encoding);
        sheet.setVerticallyCenter(true);
        sheet.setDefaultColumnWidth((short) 10);
        HSSFCellStyle tableStyle = getTableStyle(workBook,true);
        HSSFCellStyle tdStyle = getTableStyle(workBook,false);
        if(null!=thTables){//th表格
            //当前开始行,当前结束行,一共多少列
            createRow((thTables[0]-1), thTables[1],thTables[2],tableStyle,sheet);
        }
        if(null!=ths){//th跨行跨列,合并单元格
            for(String str:ths){
                String[] args = str.split(",");
                //第0行 第0列开始 ;跨2行 到 第0列结束
                mergedRegion(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1,
                        Integer.parseInt(args[3]) - 1,
                        Integer.parseInt(args[2]) - 1, sheet);// 合并单元格
                setValue(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1, 
                        args[4], 
                        tableStyle,cellType, sheet);
            }
        }
        if(null!=tdTables){//当前开始行,当前结束行,一共多少列
            createRow((tdTables[0]-1), tdTables[1],tdTables[2],tdStyle,sheet);
        }
        if(null!=tdVals){//td对应的值
            for(int i=0;i<tdVals.size();i++){
                Map<String,String > mapObj = tdVals.get(i);
                for (Map.Entry<String, String> entry : mapObj.entrySet()){
                     String key=entry.getKey();//次方法获取键值对的名称 
                     String value=entry.getValue();//次方法获取键值对的值 
                     String[] args = key.split(",");
                     mergedRegion(Integer.parseInt(args[0]) - 1,
                                Integer.parseInt(args[1]) - 1,
                                Integer.parseInt(args[3]) - 1,
                                Integer.parseInt(args[2]) - 1, sheet);// 合并单元格
                     setValue(Integer.parseInt(args[0]) - 1,
                                Integer.parseInt(args[1]) - 1, 
                                value, 
                                tdStyle,cellType, sheet);
                }
            }
        }
    }
        return workBook;
}
    
    
    
    /**
     * 导出多表头excel
     * TODO
     * @param thTables
     * @param th
     * @param startLine
     * @param method
     * @param class1
     * @param l1
     * @param sheet
     * @param tableStyle
     * @param tdStyle
     * @param idx 合并cell 从1开始 同行
     * @param num  合并cell 同行
     * @param idxRow 开始行  合并cell   同列
     * @param eidx  结束行
     * @param colNum 合并的cell列
     * TRAVLER
     * 2015年12月1日上午11:06:35
     */
    public void exportExcelMoreTh(int[] thTables, List<String> ths,int startLine,String[] method,Class clazz,List<?> list,HSSFSheet sheet,HSSFCellStyle tableStyle,HSSFCellStyle tdStyle,Integer idx,Integer num,Integer idxRow,Integer eidx,Integer colNum) {
        this.createMoreTablesheet(thTables, ths, startLine, method, clazz, list, sheet, tableStyle, tdStyle,idx,num,idxRow,eidx,colNum);
        
    }
    /**
     * 处理多表头sheet
     * TODO
     * @param thTables
     * @param ths
     * @param startLine
     * @param method
     * @param clazz
     * @param list
     * @param sheet
     * @param tableStyle
     * @param tdStyle
     * @param idx 合并cell 从1开始 同行
     * @param num  合并cell 同行
     * @param idxRow 开始行  合并cell   同列
     * @param eidx  结束行
     * @param colNum 合并的cell列
     * TRAVLER
     * 2015年12月1日上午11:08:44
     */
    private void createMoreTablesheet(int[] thTables, List<String> ths, int startLine, String[] method, Class clazz,
            List<?> list, HSSFSheet sheet, HSSFCellStyle tableStyle, HSSFCellStyle tdStyle, Integer idx, Integer num,Integer idxRow,Integer eidx,Integer colNum) {
        HSSFCell cell1=null;
        if(null!=thTables){//th表格
            //当前开始行,当前结束行,一共多少列
            createRow((thTables[0]-1), thTables[1],thTables[2],tableStyle,sheet);
        }
        if(null!=ths){//th跨行跨列,合并单元格
            for(String str:ths){
                String[] args = str.split(",");
                //第0行 第0列开始 ;跨2行 到 第0列结束
                mergedRegion(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1,
                        Integer.parseInt(args[3]) - 1,
                        Integer.parseInt(args[2]) - 1, sheet);// 合并单元格
                setValue(Integer.parseInt(args[0]) - 1,
                        Integer.parseInt(args[1]) - 1, 
                        args[4], 
                        tdStyle,cellType, sheet);
            }
        }
        
        for(Object o:list){
            HSSFRow row = sheet.createRow(startLine++);
            for (short cellIndex = 0; cellIndex < thTables[2]; cellIndex++) {
                HSSFCell cell = row.createCell(cellIndex);
                cell.setEncoding(encoding);
                if (tdStyle != null) {
                    cell.setCellStyle(tdStyle);
                }
                cell.setCellType(cellType);
                cell.setCellValue("");
            }
            if(idx!=null){
                mergedRegion(row.getRowNum(),
                        idx-1,
                        row.getRowNum(),
                        num-1, sheet);// 合并单元格
            }
            BigDecimal v=null;
            Integer index=null;
            Object value=null;
            for(int i=0;i<method.length;i++){
                Method m;
                try {
                    m = clazz.getDeclaredMethod(method[i]);
                    Type rType=m.getGenericReturnType();
                    if(rType==Double.TYPE || rType==Float.TYPE){
                        value=m.invoke(o);
                        if(value!=null){
                            value=MathUtil.roundHalfUp((Double) value, 2);
                        }else{
                            value="0.0";
                        }
                    }else if(rType==Integer.TYPE || rType==Long.TYPE ||rType==Short.TYPE){
                        value= m.invoke(o)!=null?m.invoke(o).toString():"0";
                    }else{
                        value= m.invoke(o)!=null?m.invoke(o).toString().trim():"";
                        try {
                            if(!value.equals("")){
                                v=new BigDecimal(value.toString());
                                Integer stat=v.compareTo(new BigDecimal(1000000000));
                                if(stat>=1){
                                    //存在大数字原样输出
                                }else{
                                    value=(v.setScale(2, BigDecimal.ROUND_HALF_UP)).toString();
                                    index=value.toString().indexOf('.');
                                    String d=value.toString().substring(index, value.toString().length());
                                    double ys=Double.parseDouble(d);
                                    if(ys==0){
                                        value=value.toString().substring(0, index);
                                    }
                                }
                            }
                        } catch (Exception e) {
                            //e.printStackTrace();
                        }
                    }
                    //合并同列数据
                    if(idxRow!=null&&i==colNum){
                        mergedRegion(idxRow,
                                i,
                                eidx,
                                i, sheet);// 合并单元格
                    }
                    cell1=row.getCell((short) i);
                    cell1.setEncoding(HSSFCell.ENCODING_UTF_16);
                    cell1.setCellValue(value.toString());
                } catch (Exception e) {
                    e.printStackTrace();
                } 
            }
        }
        
        
    }
    
}