派生自 projectDept/qhighschool

Administrator
2022-11-18 b6a92bcd70d2edfb8bf2a2e784b37e1fcd036c10
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
package com.qxueyou.scc.base.util;
 
//import java.io.FileNotFoundException;
//import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
//import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
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.HSSFRichTextString;
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.HSSFColor;
 
import com.qxueyou.scc.base.model.ExcelExportParam;
//import com.qxueyou.scc.user.model.UserRegistration;
//import com.qxueyou.scc.user.model.UserRegistrationExport;
 
/**
 * 
 * 
 * @param <T>
 * Ó¦Ó÷ºÐÍ£¬´ú±íÈÎÒâÒ»¸ö·ûºÏjavabean·ç¸ñµÄÀà
 * booleanÐ͵ÄÊôÐÔxxxµÄgetÆ÷·½Ê½ÎªgetXxx(),¶ø²»ÊÇisXxx()
 */
public class ExcelExportUtils<T> {
    
    private static Logger log = LogManager.getLogger("ExcelExport");
    
    /**
     * ÉèÖñêÌâÑùʽ,×ÖÌå
     * @param objStyle
     * @param workbook
     */
    private void initTitleCellStyle(HSSFCellStyle objStyle,HSSFWorkbook workbook){
        objStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        objStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        objStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        objStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        objStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        objStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        objStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        
        // Éú³ÉÒ»¸ö×ÖÌå
        HSSFFont font = workbook.createFont();
        font.setFontHeightInPoints((short) 12);
        font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        // °Ñ×ÖÌåÓ¦Óõ½±êÌâÑùʽ
        objStyle.setFont(font);
    }
    
    /**
     * ÉèÖõ¼³öÄÚÈÝÑùʽ
     * @param objStyle
     * @param workbook
     */
    private void initContentCellStyle(HSSFCellStyle objStyle,HSSFWorkbook workbook){
        objStyle.setFillForegroundColor(HSSFColor.WHITE.index);
        objStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
        objStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);
        objStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);
        objStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);
        objStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);
        objStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
    }
    
    /**
     * ÊÇ·ñÖ¸¶¨Áпí
     * @param sheet
     * @param lstColumnWidth
     */
    private void initColumnWidth(HSSFSheet sheet,List<Integer> lstColumnWidth){
        if(lstColumnWidth != null){
            for(int i=0;i<lstColumnWidth.size();i++){
                sheet.setColumnWidth(i, lstColumnWidth.get(i));
            }    
        }
    }
    
    /**
     * ³õʼ»¯µ¼³ö±êÌâ
     * @param row
     * @param headers
     * @param titleStyle
     */
    private void initTitleRow(HSSFRow row,String[] headers,HSSFCellStyle titleStyle,List<String> lstColumn){
        for (int i = 0; i < headers.length && (null == lstColumn || i <= lstColumn.size()); i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellStyle(titleStyle);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }
    }
    
    /**
     * °´ÕÕT£¬µ¼³öËùÓÐÁÐÄÚÈÝ
     * @param objExcelExportParam
     */
    public void exportExcel(ExcelExportParam<T> objExcelExportParam) {
        this.exportExcel(objExcelExportParam,false);
    }
    
    /**
     * Ö¸¶¨Áе¼³ö
     * @param objExcelExportParam
     */
    public void exportExcelByColomn(ExcelExportParam<T> objExcelExportParam) {
        this.exportExcel(objExcelExportParam,true);
    }
    
    /**
     * µ¼³öexcelʵÏÖ
     * @param objExcelExportParam
     * @param exportByCol
     */
    public void exportExcel(ExcelExportParam<T> objExcelExportParam,boolean exportByCol){
        //»ñÈ¡²ÎÊý£º
        String title = objExcelExportParam.getTitle();
        Collection<T>   colData = objExcelExportParam.getColData();
        OutputStream out = objExcelExportParam.getOut();
        String pattern = objExcelExportParam.getPattern();
        if(null == pattern){
            pattern = "yyyy-MM-dd";
        }
        boolean numberFormat = objExcelExportParam.getNumberFormat();
        List<String> lstColumn = null;
        if(exportByCol){
            lstColumn = objExcelExportParam.getLstColumn();
        }
        
        // ÉùÃ÷Ò»¸ö¹¤×÷±¡
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = null;
        // Éú³ÉÒ»¸ö±í¸ñ
        if(StringUtils.isNotBlank(title)){
            sheet = workbook.createSheet(title);
        }else{
            sheet = workbook.createSheet("Sheet1");
        }
        // ÉèÖñí¸ñĬÈÏÁпí¶ÈΪ18¸ö×Ö½Ú
        sheet.setDefaultColumnWidth(18);
        // ÉèÖñí¸ñĬÈÏÐи߶È
        sheet.setDefaultRowHeight((short)300);
        //ÊÇ·ñÖ¸¶¨Áпí
        initColumnWidth(sheet,objExcelExportParam.getLstColumnWidth());
        // ±êÌâÑùʽ
        HSSFCellStyle titleStyle = workbook.createCellStyle();
        initTitleCellStyle(titleStyle,workbook);
        // ÄÚÈÝÑùʽ
        HSSFCellStyle contentStyle = workbook.createCellStyle();
        initContentCellStyle(contentStyle,workbook);
        // ²úÉú±í¸ñ±êÌâÐÐ
        HSSFRow row = sheet.createRow(0);
        initTitleRow(row,objExcelExportParam.getHeaders(),titleStyle,lstColumn);
 
        // ±éÀú¼¯ºÏÊý¾Ý£¬²úÉúÊý¾ÝÐÐ
        Iterator<T> it = colData.iterator();
        int index = 0;
        while (it.hasNext()) {
            index++;
            row = sheet.createRow(index);
            T t = (T) it.next();
            
            //ĬÈϸøÐòºÅÁÐ
            HSSFCell cell = row.createCell(0);
            cell.setCellStyle(contentStyle);
            HSSFRichTextString richString = new HSSFRichTextString(String.valueOf(index));
            HSSFFont font3 = workbook.createFont();
            richString.applyFont(font3);
            cell.setCellValue(richString);
            
            //Ö¸¶¨Áе¼³öʹÓÃ
            if(exportByCol){
                for(int j = 0; j < lstColumn.size() ; j++ ){
                    doExportExcel(row,contentStyle,pattern,numberFormat,workbook,lstColumn.get(j),t,j+1);
                }
            }else{
                // ÀûÓ÷´É䣬¸ù¾ÝjavabeanÊôÐÔµÄÏȺó˳Ðò£¬¶¯Ì¬µ÷ÓÃgetXxx()·½·¨µÃµ½ÊôÐÔÖµ
                Field[] fields = t.getClass().getDeclaredFields();
                for (int i = 0; i < fields.length; i++) {
                    if(!"serialVersionUID".equals(fields[i].getName())){
                        doExportExcel(row,contentStyle,pattern,numberFormat,workbook,fields[i].getName(),t,i);
                    }
                }
            }
        }
        try {
            workbook.write(out);
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            
        }
    }
    
    private void doExportExcel(HSSFRow row,HSSFCellStyle contentStyle,String pattern,boolean numberFormat,HSSFWorkbook workbook,String fieldName,T t,int i){
        HSSFCell cell = row.createCell(i);
        cell.setCellStyle(contentStyle);
        //booleanÀàÐÍĬÈÏʹÓÃget£¬¶ø·Çis
        String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
        try {
            @SuppressWarnings("rawtypes")
            Class tCls = t.getClass();
            @SuppressWarnings("unchecked")
            Method getMethod = tCls.getMethod(getMethodName,new Class[] {});
            Object value = getMethod.invoke(t, new Object[] {});
            // ¸ñʽ»¯ÄÚÈÝ
            String textValue = "";
            if (value instanceof Date) {
                Date date = (Date) value;
                SimpleDateFormat sdf = new SimpleDateFormat(pattern);
                textValue = sdf.format(date);
            }else{
                if(value != null){
                    textValue = String.valueOf(value);
                }
            }
            //ÀûÓÃÕýÔò±í´ïʽÅжÏtextValueÊÇ·ñÈ«²¿ÓÉÊý×Ö×é³É
            if (null != textValue) {
                Pattern p = Pattern.compile("^//d+(//.//d+)?$");
                Matcher matcher = p.matcher(textValue);
                if (matcher.matches() && numberFormat) {
                    // ÊÇÊý×Öµ±×÷double´¦Àí
                    cell.setCellValue(Double.parseDouble(textValue));
                } else {
                    HSSFRichTextString richString = new HSSFRichTextString(textValue);
                    HSSFFont font3 = workbook.createFont();
                    richString.applyFont(font3);
                    cell.setCellValue(richString);
                }
            }
        } catch (SecurityException e) {
            log.error(e);
        } catch (NoSuchMethodException e) {
            log.error(e);
        } catch (IllegalArgumentException e) {
            log.error(e);
        } catch (IllegalAccessException e) {
            log.error(e);
        } catch (InvocationTargetException e) {
            log.error(e);
        } finally {
            
        }
    }
    
    public static void main(String[] args) {
        System.out.println(new Date().getTime());
        /*// ²âÊÔѧÉú
        ExcelExportUtils<UserRegistrationExport> ex = new ExcelExportUtils<UserRegistrationExport>();
        String[] headers = { "ÐòºÅ","°à¼¶", "ÐÕÃû", "ÐÔ±ð" ,"±¨ÃûÂë" ,"ÊÖ»úºÅ" ,"ÆäËûÁªÏµ·½Ê½","״̬"};
        List<UserRegistrationExport> dataset = new ArrayList<UserRegistrationExport>();
        UserRegistrationExport u = new UserRegistrationExport();
        u.setClassName("¸ß¼¶JAVA¹¤³Ìʦһ°à");
        u.setMobilePhone("13312886688");
        u.setSalesCode("123.34");
        u.setSex(false);
        u.setStatus(UserRegistration.STATUS_ACTIVE);
        u.setUserName("ÁõÃÀÐÒ×Ó");
        dataset.add(u);
        ExcelExportParam<UserRegistrationExport> obj = new ExcelExportParam<UserRegistrationExport>();
        obj.setColData(dataset);
        obj.setHeaders(headers);
        
        try {
            OutputStream out = new FileOutputStream("D://testExportExcelAll.xls");
            obj.setOut(out);
            ex.exportExcel(obj);
            out.close();
            System.out.println("excelµ¼³ö³É¹¦£¡");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try {
            OutputStream out = new FileOutputStream("D://testExportExcelByCol.xls");
            List<String> lst = new ArrayList<String>();
            lst.add("className");
            lst.add("userName");
            obj.setLstColumn(lst);
            obj.setOut(out);
            ex.exportExcelByColomn(obj);
            out.close();
            System.out.println("excelÖ¸¶¨Áе¼³ö³É¹¦£¡");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }
}