导出Excel工具类

  1 import java.io.OutputStream;
  2 import java.lang.reflect.Method;
  3 import java.text.SimpleDateFormat;
  4 import java.util.Date;
  5 import java.util.List;
  6 import java.util.Map;
  7 
  8 import javax.servlet.http.HttpServletResponse;
  9 
 10 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 11 import org.apache.poi.hssf.util.HSSFColor;
 12 import org.apache.poi.ss.usermodel.Cell;
 13 import org.apache.poi.ss.usermodel.CellStyle;
 14 import org.apache.poi.ss.usermodel.Font;
 15 import org.apache.poi.ss.usermodel.Row;
 16 import org.apache.poi.ss.usermodel.Sheet;
 17 import org.apache.poi.ss.usermodel.Workbook;
 18 import org.apache.poi.ss.util.CellRangeAddress;
 19 import org.apache.poi.xssf.usermodel.XSSFWorkbook;
 20 
 21 /**
 22  * Description: 导出工具类
 23  * All Rights Reserved.
 24  */
 25 public class ExcelExprot {
 26     @SuppressWarnings("unchecked")
 27     public void exportExcel(HttpServletResponse response, String fileName,
 28         ExcelModel... excelModels) {
 29     // 输出流
 30     OutputStream os = null;
 31     // excel文件
 32     Workbook wb = null;
 33     // excel工作表
 34     Sheet st;
 35 
 36     try {
 37         os = response.getOutputStream();
 38         if ((fileName.trim().substring(fileName.indexOf(".")))
 39             .equals(".xlsx"))
 40         wb = new XSSFWorkbook();
 41         else
 42         wb = new HSSFWorkbook();
 43         for (ExcelModel excelModel : excelModels) {
 44         if (excelModel.getSheetName() != null
 45             && excelModel.getSheetName().trim().length() != 0) {
 46             st = wb.createSheet(excelModel.getSheetName());
 47         } else {
 48             st = wb.createSheet();
 49         }
 50         Font font = wb.createFont();
 51         font.setBoldweight(Font.BOLDWEIGHT_BOLD);
 52         // 设置文字蓝色 且剧中
 53         CellStyle styleBlueFontNotWrap = wb.createCellStyle();
 54         styleBlueFontNotWrap
 55             .setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
 56         styleBlueFontNotWrap.setFont(font);
 57         styleBlueFontNotWrap.setAlignment(CellStyle.VERTICAL_CENTER);
 58         styleBlueFontNotWrap.setAlignment(CellStyle.ALIGN_CENTER);
 59         styleBlueFontNotWrap.setWrapText(false);
 60 
 61         Boolean cbFlag = excelModel.getCallBack() != null;
 62         Row row = null;
 63         Cell cell = null;
 64         int rowcursor = 0;
 65         int columncursor = 0;
 66         row = st.createRow(rowcursor);
 67         row.setHeight((short) 500);
 68         for (int i = 0; i < excelModel.getHeaders().length; i++) {
 69             st.setColumnWidth(i, 7000);
 70             columncursor = i;
 71             String value = excelModel.getHeaders()[i];
 72             cell = row.createCell(columncursor);
 73             cell.setCellValue(value);
 74             cell.setCellStyle(styleBlueFontNotWrap);
 75             if (cbFlag) {
 76             excelModel.getCallBack().execute(rowcursor,
 77                 columncursor, cell, value);
 78             }
 79         }
 80         rowcursor++;
 81         List<?> datas = excelModel.getDatas();
 82         if (datas != null && datas.size() > 0) {
 83             while (true) {
 84             if (datas.size() + 1 == rowcursor) {
 85                 break;
 86             }
 87             row = st.createRow(rowcursor);
 88             Class<?> cls = excelModel.getDataCls();
 89             if (cls.getName().equals("java.util.Map")) {
 90                 Map<String, Object> map = (Map<String, Object>) datas
 91                     .get(rowcursor - 1);
 92                 for (int i = 0; i < excelModel.getBodys().length; i++) {
 93                 columncursor = i;
 94                 Object value = map
 95                     .get(excelModel.getBodys()[i]);
 96                 createCell(excelModel, cbFlag, row, rowcursor,
 97                     columncursor, value);
 98                 }
 99             } else {
100                 Object obj = datas.get(rowcursor - 1);
101                 String[] bodys = excelModel.getBodys();
102                 for (int i = 0; i < bodys.length; i++) {
103                 columncursor = i;
104                 String methodName = "get"
105                     + bodys[i].substring(0, 1)
106                         .toUpperCase()
107                     + bodys[i].substring(1);
108                 Method met = cls.getMethod(methodName);
109                 Object value = met.invoke(obj);
110                 createCell(excelModel, cbFlag, row, rowcursor,
111                     columncursor, value);
112                 }
113             }
114             rowcursor++;
115             }
116         }
117         }
118 
119         response.setContentType("application/msexcel;charset=UTF-8");
120         // 定义输出类型
121         fileName = new String(fileName.getBytes("gb2312"), "ISO-8859-1");
122         response.setHeader("Content-disposition", "attachment; filename="
123             + fileName);
124         wb.write(os);
125     } catch (Exception e) {
126         e.printStackTrace();
127     } finally {
128         try {
129         if (os != null)
130             os.close();
131         } catch (Exception e2) {
132         e2.printStackTrace();
133         }
134     }
135     }
136     
137     
138     /**
139      * <p>Title: exportExcelExtend  </p>
140      * Description: 合并单元格 143      * @param response
144      * @param fileName
145      * @param excelModels
146       */
147      @SuppressWarnings("unchecked")
148      public void exportExcelExtends(HttpServletResponse response,String fileName, String[] header1,String[] header2,
149          ExcelModel... excelModels) {
150      // 输出流
151      OutputStream os = null;
152      // excel文件
153      Workbook wb = null;
154      // excel工作表
155      Sheet st;
156 
157      try {
158          os = response.getOutputStream();
159          if ((fileName.trim().substring(fileName.indexOf(".")))
160              .equals(".xlsx"))
161          wb = new XSSFWorkbook();
162          else
163          wb = new HSSFWorkbook();
164          for (ExcelModel excelModel : excelModels) {
165          if (excelModel.getSheetName() != null
166              && excelModel.getSheetName().trim().length() != 0) {
167              st = wb.createSheet(excelModel.getSheetName());
168          } else {
169              st = wb.createSheet();
170          }
171          Font font = wb.createFont();
172          font.setBoldweight(Font.BOLDWEIGHT_BOLD);
173          // 设置文字蓝色 且剧中
174          CellStyle styleBlueFontNotWrap = wb.createCellStyle();
175          styleBlueFontNotWrap
176              .setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
177          styleBlueFontNotWrap.setFont(font);
178          styleBlueFontNotWrap.setAlignment(CellStyle.VERTICAL_CENTER);
179          styleBlueFontNotWrap.setAlignment(CellStyle.ALIGN_CENTER);
180          styleBlueFontNotWrap.setWrapText(false);
181 
182          Boolean cbFlag = excelModel.getCallBack() != null;
183          Row row = null;
184          Cell cell = null;
185          int rowcursor = 0;
186          int columncursor = 0;
187          
188          st.addMergedRegion(new CellRangeAddress(0,1,0,0)); 
189          st.addMergedRegion(new CellRangeAddress(0,1,1,1)); 
190          st.addMergedRegion(new CellRangeAddress(0,0,2,5)); 
191          st.addMergedRegion(new CellRangeAddress(0,0,6,9)); 
192          
193          row = st.createRow(rowcursor);
194          row.setHeight((short) 400);
195          for (int i = 0; i < header1.length; i++) {
196              st.setColumnWidth(i, 7000);
197              columncursor = i;
198              String value = header1[i];
199              cell = row.createCell(columncursor);
200              cell.setCellValue(value);
201              cell.setCellStyle(styleBlueFontNotWrap);
202              if (cbFlag) {
203              excelModel.getCallBack().execute(rowcursor,
204                  columncursor, cell, value);
205              }
206          }
207          rowcursor++;
208          row = st.createRow(rowcursor);
209          row.setHeight((short) 400);
210          for (int i = 1; i < header2.length; i++) {
211              st.setColumnWidth(i, 7000);
212              columncursor = i;
213              String value = header2[i];
214              cell = row.createCell(columncursor);
215              cell.setCellValue(value);
216              cell.setCellStyle(styleBlueFontNotWrap);
217              if (cbFlag) {
218              excelModel.getCallBack().execute(rowcursor,
219                  columncursor, cell, value);
220              }
221          }
222          rowcursor++;
223          List<?> datas = excelModel.getDatas();
224          if (datas != null && datas.size() > 0) {
225              while (true) {
226              if (datas.size() + 2 == rowcursor) {
227                  break;
228              }
229              row = st.createRow(rowcursor);
230              Class<?> cls = excelModel.getDataCls();
231              if (cls.getName().equals("java.util.Map")) {
232                  Map<String, Object> map = (Map<String, Object>) datas
233                      .get(rowcursor - 2);
234                  for (int i = 0; i < excelModel.getBodys().length; i++) {
235                  columncursor = i;
236                  Object value = map
237                      .get(excelModel.getBodys()[i]);
238                  createCell(excelModel, cbFlag, row, rowcursor,
239                      columncursor, value);
240                  }
241              } else {
242                  Object obj = datas.get(rowcursor - 2);
243                  String[] bodys = excelModel.getBodys();
244                  for (int i = 0; i < bodys.length; i++) {
245                  columncursor = i;
246                  String methodName = "get"
247                      + bodys[i].substring(0, 1)
248                          .toUpperCase()
249                      + bodys[i].substring(1);
250                  Method met = cls.getMethod(methodName);
251                  Object value = met.invoke(obj);
252                  createCell(excelModel, cbFlag, row, rowcursor,
253                      columncursor, value);
254                  }
255              }
256              rowcursor++;
257              }
258          }
259          }
260          response.setContentType("application/msexcel;charset=UTF-8");
261          // 定义输出类型
262          fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
263          response.setHeader("Content-disposition", "attachment; filename="
264              + fileName);
265          wb.write(os);
266      } catch (Exception e) {
267          e.printStackTrace();
268      } finally {
269          try {
270          if (os != null)
271              os.close();
272          } catch (Exception e2) {
273          e2.printStackTrace();
274          }
275      }
276      }
277     
278 
279     private void createCell(ExcelModel excelModel, Boolean cbFlag, Row row,
280         int rowcursor, int columncursor, Object value) {
281     if (value != null) {
282         Cell cell = row.createCell(columncursor);
283         try {
284         if (value.getClass().getName().equals("java.util.Date")) {
285             if (excelModel.getDateFormat() != null) {
286             SimpleDateFormat df = new SimpleDateFormat(
287                 excelModel.getDateFormat());
288             cell.setCellValue(df.format((Date) value));
289             } else {
290             cell.setCellValue((Date) value);
291             }
292         } else if (value.getClass().getName().equals("boolean")
293             || value.getClass().getName()
294                 .equals("java.lang.Boolean")) {
295             cell.setCellValue(Double.valueOf(value.toString()));
296         } else {
297             cell.setCellValue(value.toString());
298         }
299         } catch (Exception e) {
300         e.printStackTrace();
301         }
302         if (cbFlag) {
303         excelModel.getCallBack().execute(rowcursor, columncursor, cell,
304             value);
305         }
306     }
307     }
308 }
 1 import org.apache.poi.ss.usermodel.Cell;
 2 
 3 /**
 4  * Description: excel的回调工具类 
 5  * All Rights Reserved.
 6  */
 7 public interface ExcelCallBack {
 8     /**
 9      * Description: 可根据行号 或者列号来操作单元格的数据或者样式11      * @param row
12      * @param column
13      * @param cell
14      * @param value
15      */
16     public void execute(int row, int column, Cell cell, Object value);
17 }
 1 import java.util.List;
 2 
 3 /**
 4  * Description: excelModel
 5  * All Rights Reserved.
 6  */
 7 public class ExcelModel {
 8     // sheet 页名称
 9     private String sheetName;
10     // 头名称数组
11     private String[] headers;
12     // 数据顺序 实体类属性或者map的key
13     private String[] bodys;
14     // 数据集合
15     private List<?> datas;
16     // 数据类型 map 或者实体类
17     private Class<?> dataCls;
18     // 回调函数 可以修改对应cell的值 也可以添加样式等
19     private ExcelCallBack callBack;
20     // 日期格式
21     private String dateFormat;
22 
23     public String getSheetName() {
24     return sheetName;
25     }
26 
27     public void setSheetName(String sheetName) {
28     this.sheetName = sheetName;
29     }
30 
31     public String[] getHeaders() {
32     return headers;
33     }
34 
35     public void setHeaders(String[] headers) {
36     this.headers = headers;
37     }
38 
39     public void setHeader(String... headers) {
40     this.headers = headers;
41     }
42 
43     public String[] getBodys() {
44     return bodys;
45     }
46 
47     public void setBodys(String[] bodys) {
48     this.bodys = bodys;
49     }
50 
51     public void setBody(String... bodys) {
52     this.bodys = bodys;
53     }
54 
55     public ExcelCallBack getCallBack() {
56     return callBack;
57     }
58 
59     public void setCallBack(ExcelCallBack callBack) {
60     this.callBack = callBack;
61     }
62 
63     public List<?> getDatas() {
64     return datas;
65     }
66 
67     public void setDatas(List<?> datas) {
68     this.datas = datas;
69     }
70 
71     public Class<?> getDataCls() {
72     return dataCls;
73     }
74 
75     public void setDataCls(Class<?> dataCls) {
76     this.dataCls = dataCls;
77     }
78 
79     public String getDateFormat() {
80     return dateFormat;
81     }
82 
83     public void setDateFormat(String dateFormat) {
84     this.dateFormat = dateFormat;
85     }
86 }
    private String methodName(Result result, String respResult,List<Object> list) {
        String period =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String excelName = null;
        ExcelExprot excelExprot = new ExcelExprot();
        // 构建参数
        ExcelModel excelModel = new ExcelModel();
        
        excelName = "";
        excelModel.setSheetName("");
        
        excelModel.setHeader("", "", "", "",""); 
        excelModel.setBody("", "", "", "","");
        
        excelModel.setDatas(list);
        excelModel.setDataCls(Object.class);
        try {
            excelModel.setCallBack(new ExcelCallBack() {
                @Override
                // 可根据行号 或者列号来操作单元格的数据或者样式
                public void execute(int row, int column, Cell cell, Object value) {
                                            Class<?> cls = value.getClass();
                    if (cls.equals(java.util.Date.class) || cls.equals(java.sql.Timestamp.class)) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        cell.setCellValue(sdf.format((Date) value));
                    }else {
                        cell.setCellValue(value.toString());
                    }
                }
            });
            // 调用导出方法 response测试传入null
            excelExprot.exportExcel(response, excelName  + period + ".xlsx", excelModel);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            respResult = result.error(e.getMessage());
        }
        return respResult;
    }
原文地址:https://www.cnblogs.com/yanduanduan/p/10038549.html