用poi类,先做好模板,用poi填写
package com.paic.gcc.service.offwork.util;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletResponse;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
/**
导入导出Excel工具类
*
*/
public class ExcelUtil {
/**
@throws ExcelException
*/
public static void listToExcel(List list, Map fieldMap, String sheetName, int sheetSize, OutputStream out)
throws ExcelException {
if (list == null || list.isEmpty()) {
throw new ExcelException("数据源中没有任何数据");
}
if (sheetSize > 65535 || sheetSize < 1) {
sheetSize = 65535;
}
// 创建工作簿并发送到OutputStream指定的地方
WritableWorkbook wwb;
try {
wwb = Workbook.createWorkbook(out);
// 因为2003的Excel一个工作表最多可以有65536条记录,除去列头剩下65535条
// 所以如果记录太多,需要放到多个工作表中,其实就是个分页的过程
// 1.计算一共有多少个工作表
double sheetNum = Math.ceil(list.size() / new Integer(sheetSize).doubleValue());
// 2.创建相应的工作表,并向其中填充数据
for (int i = 0; i < sheetNum; i++) {
// 如果只有一个工作表的情况
if (1 == sheetNum) {
WritableSheet sheet = wwb.createSheet(sheetName, i);
fillSheet(sheet, list, fieldMap, 0, list.size() - 1);
// 有多个工作表的情况
} else {
WritableSheet sheet = wwb.createSheet(sheetName + (i + 1), i);
// 获取开始索引和结束索引
int firstIndex = i * sheetSize;
int lastIndex = (i + 1) * sheetSize - 1 > list.size() - 1 ? list.size() - 1 : (i + 1) * sheetSize - 1;
// 填充工作表
fillSheet(sheet, list, fieldMap, firstIndex, lastIndex);
}
}
wwb.write();
wwb.close();
} catch (Exception e) {
e.printStackTrace();
// 如果是ExcelException,则直接抛出
if (e instanceof ExcelException) {
throw (ExcelException) e;
// 否则将其它异常包装成ExcelException再抛出
} else {
throw new ExcelException("导出Excel失败");
}
}
}
/**
@throws ExcelException
*/
public static void listToExcel(List list, Map fieldMap, String sheetName, OutputStream out)
throws ExcelException {
listToExcel(list, fieldMap, sheetName, 65535, out);
}
/**
@throws ExcelException
*/
public static void listToExcel(List list, Map fieldMap, String sheetName, int sheetSize,
HttpServletResponse response) throws ExcelException {
// 设置默认文件名为当前时间:年月日时分秒
String fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
// 设置response头信息
response.reset();
response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xls");
// 创建工作簿并发送到浏览器
try {
OutputStream out = response.getOutputStream();
listToExcel(list, fieldMap, sheetName, sheetSize, out);
} catch (Exception e) {
e.printStackTrace();
// 如果是ExcelException,则直接抛出
if (e instanceof ExcelException) {
throw (ExcelException) e;
// 否则将其它异常包装成ExcelException再抛出
} else {
throw new ExcelException("导出Excel失败");
}
}
}
/**
@throws ExcelException
*/
public static void listToExcel(List list, Map fieldMap, String sheetName, HttpServletResponse response)
throws ExcelException {
listToExcel(list, fieldMap, sheetName, 65535, response);
}
/*
@return 字段值
*/
private static Object getFieldValueByName(String fieldName, Object o) throws Exception {
Object value = null;
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
value = field.get(o);
} else {
throw new ExcelException(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
return value;
}
/**
@return 字段
*/
private static Field getFieldByName(String fieldName, Class<?> clazz) {
// 拿到本类的所有字段
Field[] selfFields = clazz.getDeclaredFields();
// 如果本类中存在该字段,则返回
for (Field field : selfFields) {
if (field.getName().equals(fieldName)) {
return field;
}
}
// 否则,查看父类中是否存在此字段,如果有则返回
Class<?> superClazz = clazz.getSuperclass();
if (superClazz != null && superClazz != Object.class) {
return getFieldByName(fieldName, superClazz);
}
// 如果本类和父类都没有,则返回空
return null;
}
/**
@throws Exception
*/
private static Object getFieldValueByNameSequence(String fieldNameSequence, Object o) throws Exception {
Object value = null;
// 将fieldNameSequence进行拆分
String[] attributes = fieldNameSequence.split("\.");
if (attributes.length == 1) {
value = getFieldValueByName(fieldNameSequence, o);
} else {
// 根据属性名获取属性对象
Object fieldObj = getFieldValueByName(attributes[0], o);
String subFieldNameSequence = fieldNameSequence.substring(fieldNameSequence.indexOf(".") + 1);
value = getFieldValueByNameSequence(subFieldNameSequence, fieldObj);
}
return value;
}
/**
对象
*/
@SuppressWarnings("unused")
private static void setFieldValueByName(String fieldName, Object fieldValue, Object o) throws Exception {
Field field = getFieldByName(fieldName, o.getClass());
if (field != null) {
field.setAccessible(true);
// 获取字段类型
Class<?> fieldType = field.getType();
// 根据字段类型给字段赋值
if (String.class == fieldType) {
field.set(o, String.valueOf(fieldValue));
} else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType)) {
field.set(o, Integer.parseInt(fieldValue.toString()));
} else if ((Long.TYPE == fieldType) || (Long.class == fieldType)) {
field.set(o, Long.valueOf(fieldValue.toString()));
} else if ((Float.TYPE == fieldType) || (Float.class == fieldType)) {
field.set(o, Float.valueOf(fieldValue.toString()));
} else if ((Short.TYPE == fieldType) || (Short.class == fieldType)) {
field.set(o, Short.valueOf(fieldValue.toString()));
} else if ((Double.TYPE == fieldType) || (Double.class == fieldType)) {
field.set(o, Double.valueOf(fieldValue.toString()));
} else if (Character.TYPE == fieldType) {
if ((fieldValue != null) && (fieldValue.toString().length() > 0)) {
field.set(o, Character.valueOf(fieldValue.toString().charAt(0)));
}
} else if (Date.class == fieldType) {
field.set(o, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(fieldValue.toString()));
} else {
field.set(o, fieldValue);
}
} else {
throw new ExcelException(o.getClass().getSimpleName() + "类不存在字段名 " + fieldName);
}
}
/**
}
/**
结束索引
*/
private static void fillSheet(WritableSheet sheet, List list, Map fieldMap, int firstIndex, int lastIndex)
throws Exception {
// 定义存放英文字段名和中文字段名的数组
String[] enFields = new String[fieldMap.size()];
String[] cnFields = new String[fieldMap.size()];
// 填充数组
int count = 0;
for (Entry entry : fieldMap.entrySet()) {
enFields[count] = entry.getKey();
cnFields[count] = entry.getValue();
count++;
}
// 填充表头
for (int i = 0; i < cnFields.length; i++) {
Label label = new Label(i, 0, cnFields[i]);
sheet.addCell(label);
}
// 填充内容
int rowNo = 1;
for (int index = firstIndex; index <= lastIndex; index++) {
// 获取单个对象
T item = list.get(index);
for (int i = 0; i < enFields.length; i++) {
Object objValue = getFieldValueByNameSequence(enFields[i], item);
String fieldValue = objValue == null ? "" : objValue.toString();
Label label = new Label(i, rowNo, fieldValue);
sheet.addCell(label);
}
rowNo++;
}
// 设置自动列宽
setColumnAutoSize(sheet, 5);
}
}