excel 导出

  1 package com.charmyin.cmstudio.common.utils;
  2 import java.io.*;
  3 import java.lang.reflect.*;
  4 import java.util.*;
  5 import java.util.regex.Matcher;
  6 import java.util.regex.Pattern;
  7 import java.text.SimpleDateFormat;
  8 
  9 import javax.swing.JOptionPane;
 10 
 11 import org.apache.poi.hssf.usermodel.*;
 12 import org.apache.poi.hssf.util.HSSFColor;
 13 
 14 /**
 15  * 利用开源组件POI3.0.2动态导出EXCEL文档 转载时请保留以下信息,注明出处!
 16  * 
 17  * @author leno
 18  * @version v1.0
 19  * @param <T>
 20  *            应用泛型,代表任意一个符合javabean风格的类
 21  *            注意这里为了简单起见,boolean型的属性xxx的get器方式为getXxx(),而不是isXxx()
 22  *            byte[]表jpg格式的图片数据
 23  */
 24 public class ExportExcel<T> {
 25 
 26     public void exportExcel(Collection<T> dataset, OutputStream out) {
 27         exportExcel("测试POI导出EXCEL文档", null, dataset, out, "yyyy-MM-dd",null);
 28     }
 29 
 30     public void exportExcel(String[] headers, Collection<T> dataset,
 31             OutputStream out) {
 32         exportExcel("测试POI导出EXCEL文档", headers, dataset, out, "yyyy-MM-dd",null);
 33     }
 34 
 35     public void exportExcel(String[] headers, Collection<T> dataset,
 36             OutputStream out, String pattern) {
 37         exportExcel("测试POI导出EXCEL文档", headers, dataset, out, pattern,null);
 38     }
 39 
 40     /**
 41      * 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
 42      * 
 43      * @param title
 44      *            表格标题名
 45      * @param headers
 46      *            表格属性列名数组
 47      * @param dataset
 48      *            需要显示的数据集合,集合中一定要放置符合javabean风格的类的对象。此方法支持的
 49      *            javabean属性的数据类型有基本数据类型及String,Date,byte[](图片数据)
 50      * @param out
 51      *            与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
 52      * @param pattern
 53      *            如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
 54      */
 55     @SuppressWarnings("unchecked")
 56     public void exportExcel(String title, String[] headers,
 57             Collection<T> dataset, OutputStream out, String pattern,String[] exportfield) {
 58         // 声明一个工作薄
 59         HSSFWorkbook workbook = new HSSFWorkbook();
 60         // 生成一个表格
 61         HSSFSheet sheet = workbook.createSheet(title);
 62         // 设置表格默认列宽度为15个字节
 63         sheet.setDefaultColumnWidth((short) 15);
 64         // 生成一个样式
 65         HSSFCellStyle style = workbook.createCellStyle();
 66         // 设置这些样式
 67         style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
 68         style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
 69         style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 70         style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 71         style.setBorderRight(HSSFCellStyle.BORDER_THIN);
 72         style.setBorderTop(HSSFCellStyle.BORDER_THIN);
 73         style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
 74         // 生成一个字体
 75         HSSFFont font = workbook.createFont();
 76         font.setColor(HSSFColor.VIOLET.index);
 77         font.setFontHeightInPoints((short) 12);
 78         font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
 79         // 把字体应用到当前的样式
 80         style.setFont(font);
 81         // 生成并设置另一个样式
 82         HSSFCellStyle style2 = workbook.createCellStyle();
 83         style2.setFillForegroundColor(HSSFColor.LIGHT_YELLOW.index);
 84         style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
 85         style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
 86         style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
 87         style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
 88         style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
 89         style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
 90         style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
 91         // 生成另一个字体
 92         HSSFFont font2 = workbook.createFont();
 93         font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);
 94         // 把字体应用到当前的样式
 95         style2.setFont(font2);
 96 
 97         // 声明一个画图的顶级管理器
 98         HSSFPatriarch patriarch = sheet.createDrawingPatriarch();
 99         // 定义注释的大小和位置,详见文档
100         HSSFComment comment = patriarch.createComment(new HSSFClientAnchor(0,
101                 0, 0, 0, (short) 4, 2, (short) 6, 5));
102 
103         // 产生表格标题行
104         HSSFRow row = sheet.createRow(0);
105         for (short i = 0; i < headers.length; i++) {
106             HSSFCell cell = row.createCell(i);
107             cell.setCellStyle(style);
108             HSSFRichTextString text = new HSSFRichTextString(headers[i]);
109             cell.setCellValue(text);
110         }
111 
112         // 遍历集合数据,产生数据行
113         Iterator<T> it = dataset.iterator();
114         int index = 0;
115         while (it.hasNext()) {
116             int tmp = 0;
117             index++;
118             row = sheet.createRow(index);
119             T t = (T) it.next();
120             // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
121             for (short i = 0; i < exportfield.length; i++) {
122                 
123                 HSSFCell cell = row.createCell(i);
124                 cell.setCellStyle(style2);
125                
126                 String fieldName = exportfield[i];
127                 String getMethodName = "get"
128                         + fieldName.substring(0, 1).toUpperCase()
129                         + fieldName.substring(1);
130                
131                 try {
132                     Class tCls = t.getClass();
133                     Method getMethod = tCls.getMethod(getMethodName,
134                             new Class[] {});
135                     Object value = getMethod.invoke(t, new Object[] {});
136                     if(value == null){
137                         continue;
138                     }
139                     // 判断值的类型后进行强制类型转换
140                     String textValue = null;
141                     // if (value instanceof Integer) {
142                     // int intValue = (Integer) value;
143                     // cell.setCellValue(intValue);
144                     // } else if (value instanceof Float) {
145                     // float fValue = (Float) value;
146                     // textValue = new HSSFRichTextString(
147                     // String.valueOf(fValue));
148                     // cell.setCellValue(textValue);
149                     // } else if (value instanceof Double) {
150                     // double dValue = (Double) value;
151                     // textValue = new HSSFRichTextString(
152                     // String.valueOf(dValue));
153                     // cell.setCellValue(textValue);
154                     // } else if (value instanceof Long) {
155                     // long longValue = (Long) value;
156                     // cell.setCellValue(longValue);
157                     // }
158                     /*if (value instanceof Boolean) {
159                         boolean bValue = (Boolean) value;
160                         textValue = "男";
161                         if (!bValue) {
162                             textValue = "女";
163                         }
164                     } else */
165                         
166                     if (value instanceof Date) {
167                         Date date = (Date) value;
168                         SimpleDateFormat sdf = new SimpleDateFormat(pattern);
169                         textValue = sdf.format(date);
170                     } 
171                     
172                    /* else if (value instanceof byte[]) {
173                         // 有图片时,设置行高为60px;
174                         row.setHeightInPoints(60);
175                         // 设置图片所在列宽度为80px,注意这里单位的一个换算
176                         sheet.setColumnWidth(i, (short) (35.7 * 80));
177                         // sheet.autoSizeColumn(i);
178                         byte[] bsValue = (byte[]) value;
179                         HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0,
180                                 1023, 255, (short) 6, index, (short) 6, index);
181                         anchor.setAnchorType(2);
182                         patriarch.createPicture(anchor, workbook.addPicture(
183                                 bsValue, HSSFWorkbook.PICTURE_TYPE_JPEG));
184                     } 
185                     */
186                     else {
187                         // 其它数据类型都当作字符串简单处理
188                         textValue = value.toString();
189                     }
190                     // 如果不是图片数据,就利用正则表达式判断textValue是否全部由数字组成
191                     if (textValue != null) {
192                         Pattern p = Pattern.compile("^//d+(//.//d+)?$");
193                         Matcher matcher = p.matcher(textValue);
194                         if (matcher.matches()) {
195                             // 是数字当作double处理
196                             cell.setCellValue(Double.parseDouble(textValue));
197                         } else {
198                             HSSFRichTextString richString = new HSSFRichTextString(
199                                     textValue);
200                             HSSFFont font3 = workbook.createFont();
201                             font3.setColor(HSSFColor.BLUE.index);
202                             richString.applyFont(font3);
203                             cell.setCellValue(richString);
204                         }
205                     }
206                 } catch (SecurityException e) {
207                     // TODO Auto-generated catch block
208                     e.printStackTrace();
209                 } catch (NoSuchMethodException e) {
210                     // TODO Auto-generated catch block
211                     e.printStackTrace();
212                 } catch (IllegalArgumentException e) {
213                     // TODO Auto-generated catch block
214                     e.printStackTrace();
215                 } catch (IllegalAccessException e) {
216                     // TODO Auto-generated catch block
217                     e.printStackTrace();
218                 } catch (InvocationTargetException e) {
219                     // TODO Auto-generated catch block
220                     e.printStackTrace();
221                 } finally {
222                     // 清理资源
223                 }
224             }
225 
226         }
227         try {
228             workbook.write(out);
229            
230         } catch (IOException e) {
231             // TODO Auto-generated catch block
232             e.printStackTrace();
233         } finally{
234              try {
235                 out.close();
236             } catch (IOException e) {
237                 // TODO Auto-generated catch block
238                 e.printStackTrace();
239             }
240         }
241     }
242 }
 1 @RequestMapping(method=RequestMethod.POST, value="/getlist")
 2     @ResponseBody
 3     public String getList(@RequestParam("exportfield[]") String[] exportfield , @RequestParam("exportheaders[]") String[] exportheaders , @RequestParam("title") String title , HttpServletRequest request){
 4         try {
 5             List<_7sEvaluateType> dataset = _7sEvaluateTypeService.getlist_7sEvaluateTypes();
 6             String filePathString = request.getSession().getServletContext().getRealPath("");
 7             OutputStream out = new FileOutputStream(filePathString+"\resources\download\report.xls");
 8             ExportExcel<_7sEvaluateType> ex = new ExportExcel<_7sEvaluateType>();
 9             ex.exportExcel(title, exportheaders, dataset, out, "yyyy-MM-dd HH:mm:ss",exportfield);
10             return ResponseUtil.getSuccessResultString();
11         } catch (FileNotFoundException e) {
12             // TODO Auto-generated catch block
13             e.printStackTrace();
14             return ResponseUtil.getFailResultString("保存过程中出错!");
15         }
16     }
 1 var exportfield = [];
 2         var exportheaders = [];
 3         function length(){
 4             var length = $("#dg").datagrid('options').columns[0].length;
 5             for(var j = 0 ; j < length ; j++){
 6                 var obj = $("#dg").datagrid('options').columns[0][j];
 7                 if(!obj.hidden){
 8                     exportfield.push(obj.field);
 9                     exportheaders.push(obj.title);
10                 }
11             }
12             var title = $("#dg").datagrid('options').title;    
13             $.post('7sEvaluateType/getlist',{exportfield:exportfield,exportheaders:exportheaders,title:title},function(result){
14                 var result = eval('('+result+')');
15                 if (result.suc){
16                     location.href = $("base").attr("href")+"resources/download/report.xls";
17                 } else {
18                     $.messager.show({    // show error message
19                         title: '错误',
20                         msg: result.errorMsg
21                     });
22                 }
23             });
24         }
原文地址:https://www.cnblogs.com/MDK-L/p/3884396.html