基于jdk1.7实现的excel导出工具类

通用excel导出工具类,基于泛型、反射、hashmap 以及基于泛型、反射、bean两种方式

import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;
import org.apache.poi.hssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;

/**
* Created by liubaofeng on 2016/7/4.
*/
public class PoiUtil {
private static Logger logger = LoggerFactory.getLogger(PoiUtil.class);
/**
* 导出Excel
* @param excelName 要导出的excel名称
* @param list 要导出的数据集合
* @param fieldMap 中英文字段对应Map,即要导出的excel表头
* @param response 使用response可以导出到浏览器
* @return
*/
public static <T> void export(String excelName,List<T> list,LinkedHashMap<String, String> fieldMap,HttpServletResponse response){

// 设置默认文件名为当前时间:年月日时分秒
if (excelName==null || excelName=="") {
excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
}
// 设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
try {
response.setHeader("Content-disposition", "attachment; filename="
+new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
} catch (UnsupportedEncodingException e1) {
logger.info(e1.getMessage());
}

try {
//创建一个WorkBook,对应一个Excel文件
HSSFWorkbook wb=new HSSFWorkbook();
//在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
HSSFSheet sheet=wb.createSheet(excelName);
//创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style=wb.createCellStyle();
//创建一个居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 填充工作表
fillSheet(sheet,list,fieldMap,style);

//将文件输出
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {

logger.error(e.getMessage(),e);
}
}
/**
* 向工作表中填充数据
* 基于map对象泛型填充数据的实现
* @param sheet
* excel的工作表名称
* @param list
* 数据源
* @param fieldMap
* 中英文字段对应关系的Map
* @param style
* 表格中的格式
* @throws Exception
* 异常
*
*/
public static <T> void fillSheet(HSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap, HSSFCellStyle style) throws Exception {
logger.info("向工作表中填充数据:fillSheet()");
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];

// 填充数组
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}

//在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);

// 填充表头
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
}

// 填充内容
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
// 获取单个对象
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = null;
if (item != null) {
HashMap hashMap = (HashMap) item;
if (hashMap.containsKey(enFields[i]))
objValue = hashMap.get(enFields[i]);
}
String fieldValue = objValue == null ? "" : objValue.toString();

row.createCell(i).setCellValue(fieldValue);
}
}
}

/**
* 导出excel基于泛型方式
* 泛型为一个一个映射对象的bean.
* @param excelName
* @param list
* @param fieldMap
* @param response
* @param <T>
*/
public static <T> void exportObject(String excelName,List<T> list,LinkedHashMap<String, String> fieldMap,HttpServletResponse response){

// 设置默认文件名为当前时间:年月日时分秒
if (excelName==null || excelName=="") {
excelName = new SimpleDateFormat("yyyyMMddhhmmss").format(
new Date()).toString();
}
// 设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
try {
response.setHeader("Content-disposition", "attachment; filename="
+new String(excelName.getBytes("gb2312"), "ISO-8859-1") + ".xls");
} catch (UnsupportedEncodingException e1) {
logger.info(e1.getMessage());
}

try {
//创建一个WorkBook,对应一个Excel文件
HSSFWorkbook wb=new HSSFWorkbook();
//在Workbook中,创建一个sheet,对应Excel中的工作薄(sheet)
HSSFSheet sheet=wb.createSheet(excelName);
//创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style=wb.createCellStyle();
//创建一个居中格式
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
// 填充工作表
fillSheetObject(sheet,list,fieldMap,style);

//将文件输出
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
} catch (Exception e) {

logger.error(e.getMessage(),e);
}
}

/**
* 填充泛型
* 基于对象方式通用填充表单方式.
*
* @param sheet
* @param list
* @param fieldMap
* @param style
* @param <T>
* @throws Exception
*/
public static <T> void fillSheetObject(HSSFSheet sheet, List<T> list,
LinkedHashMap<String, String> fieldMap, HSSFCellStyle style) throws Exception {
logger.info("向工作表中填充数据:fillSheet()");
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];

// 填充数组
int count = 0;
for (Map.Entry<String, String> entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}

//在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);

// 填充表头
for (int i = 0; i < cnFields.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(cnFields[i]);
cell.setCellStyle(style);
sheet.autoSizeColumn(i);
}

// 填充内容
for (int index = 0; index < list.size(); index++) {
row = sheet.createRow(index + 1);
// 获取单个对象
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = null;
if (item != null) {
Class c = item.getClass();
String key = enFields[i];
Method method = c.getDeclaredMethod(key);
objValue = method.invoke(item);
}
String fieldValue = objValue == null ? "" : objValue.toString();

row.createCell(i).setCellValue(fieldValue);
}
}
}
}

工具使用样例

List<EscortModel> escortModelList = escortService.selectEscortModelAll();
//定义导出excel的名字
String excelName="用户请求表";
// 获取需要转出的excle表头的map字段
LinkedHashMap<String, String> fieldMap =new LinkedHashMap<String, String>() ;
fieldMap.put("pin", "用户xx");
fieldMap.put("recmdId", "推荐xx");
fieldMap.put("userSku", "用户填写xx");
fieldMap.put("reportTime", "用户点击准或不准的时间");
fieldMap.put("recmdSku", "推荐商品xx");
fieldMap.put("skuType", "商品类别是搜索推荐还是广告推荐");
fieldMap.put("isAccurate", "推荐准确不准确");
fieldMap.put("reasonType", "用户反馈原因类型");
fieldMap.put("reason", "用户反馈原因");

PoiUtil.export(excelName, escortModelList, fieldMap, response);

借鉴相关文章或程序如下

https://github.com/T5750/poi/blob/master/src/replace/ExcelUtil.java

http://xafc2370.iteye.com/blog/1609183

http://www.iteye.com/topic/1116089

http://blog.csdn.net/u010168160/article/details/50497985

原文地址:https://www.cnblogs.com/freedommovie/p/5726904.html