Java导出Excel快速开始
标签:其它 tac core throw ack col 利用反射 object user
代码:
1 package com.scoremanager.utils;
2
3 import org.apache.poi.hssf.usermodel.*;
4
5 import javax.servlet.http.HttpServletResponse;
6 import java.io.BufferedOutputStream;
7 import java.lang.reflect.Field;
8 import java.lang.reflect.Method;
9 import java.util.Collection;
10 import java.util.Iterator;
11
12 /*
13 * 导出Excel的工具类
14 * */
15 public class ExportExcelUtils {
16 public void exportExcel(String[] headers, Collection dataset, String fileName, HttpServletResponse response) {
17 // 声明一个工作薄
18 HSSFWorkbook workbook = new HSSFWorkbook();
19 // 生成一个表格
20 HSSFSheet sheet = workbook.createSheet(fileName);
21 // 设置表格默认列宽度为15个字节
22 sheet.setDefaultColumnWidth((short) 20);
23 // 产生表格标题行
24 HSSFRow row = sheet.createRow(0);
25 for (short i = 0; i ) {
26 HSSFCell cell = row.createCell(i);
27 HSSFRichTextString text = new HSSFRichTextString(headers[i]);
28 cell.setCellValue(text);
29 }
30 try {
31 // 遍历集合数据,产生数据行
32 Iterator it = dataset.iterator();
33 int index = 0;
34 while (it.hasNext()) {
35 index++;
36 row = sheet.createRow(index);
37 T t = (T) it.next();
38 // 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
39 Field[] fields = t.getClass().getDeclaredFields();
40 for (short i = 0; i ) {
41 HSSFCell cell = row.createCell(i);
42 Field field = fields[i];
43 String fieldName = field.getName();
44 String getMethodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
45 Class tCls = t.getClass();
46 Method getMethod = tCls.getMethod(getMethodName, new Class[]{});
47 Object value = getMethod.invoke(t, new Object[]{});
48 // 判断值的类型后进行强制类型转换
49 String textValue = null;
50 // 其它数据类型都当作字符串简单处理
51 if (value != null && value != "") {
52 textValue = value.toString();
53 }
54 if (textValue != null) {
55 HSSFRichTextString richString = new HSSFRichTextString(textValue);
56 cell.setCellValue(richString);
57 }
58 }
59 }
60 getExportedFile(workbook, fileName, response);
61 } catch (Exception e) {
62 e.printStackTrace();
63 }
64 }
65
66 /**
67 * 方法说明: 指定路径下生成EXCEL文件
68 *
69 * @return
70 */
71 public void getExportedFile(HSSFWorkbook workbook, String name, HttpServletResponse response) throws Exception {
72 BufferedOutputStream fos = null;
73 try {
74 String fileName = name + ".xls";
75 response.setContentType("application/x-msdownload");
76 response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
77 fos = new BufferedOutputStream(response.getOutputStream());
78 workbook.write(fos);
79 } catch (Exception e) {
80 e.printStackTrace();
81 } finally {
82 if (fos != null) {
83 fos.close();
84 }
85 }
86 }
87 }
jar:
官网都可下载,自行百度。
Java导出Excel快速开始
标签:其它 tac core throw ack col 利用反射 object user
原文地址:https://www.cnblogs.com/daihang2366/p/13292587.html
评论