具体封装了一个下载utils类,让下载excle代码更加简洁,使用更加方便(用的是poi,不要忘了pom引入),看一下这个工具类:
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.OutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.util.CollectionUtils;
import com.ihwdz.core.DateUtils;
import com.ihwdz.core.StringUtils;
public class DownExcelUtils
{
public static final DownExcelUtils INSTANCE = new DownExcelUtils();
private final RecordProduces RECORD_PRODUCES = new RecordProduces();
public HttpServletResponse export(HttpServletResponse response , RecordProduces recordProduces) throws Exception{
OutputStream os = null;
try {
response.addHeader("Content-Disposition", "attachment;filename="+new String(recordProduces.getFileName().getBytes("gb2312"), "ISO8859-1" )+".xls");
os = response.getOutputStream();
HSSFWorkbook wb = new HSSFWorkbook();
if(!CollectionUtils.isEmpty(recordProduces.getRecords())){
boolean upOrLeft = (recordProduces.getAlignLeft() == null ? false : (!recordProduces.getAlignLeft()));
if(recordProduces.getRecords().size() == 1){
Record record = recordProduces.getRecords().get(0);
HSSFSheet sheet = wb.createSheet(getSheetName(wb,record.getSheetName()));
insetTitle(wb,sheet,record,0,0,upOrLeft);
insertData(wb, sheet,record,0,0,upOrLeft);
}else{
Integer [] area = {0,0};
if((recordProduces.getMutilSheet() == null) || recordProduces.getMutilSheet() == true){
for(int i = 0; i< recordProduces.getRecords().size(); i++ ){
Record record = recordProduces.getRecords().get(i);
HSSFSheet sheet = wb.createSheet(getSheetName(wb,record.getSheetName()));
insetTitle(wb,sheet,record,area[0],area[1],upOrLeft);
insertData(wb, sheet, record , area[0],area[1],upOrLeft);
}
}else{
HSSFSheet sheet = wb.createSheet(getSheetName(wb, recordProduces.getFileName()));
for(int i = 0; i< recordProduces.getRecords().size(); i++ ){
Record record = recordProduces.getRecords().get(i);
insetTitle(wb,sheet,record,area[0],area[1],upOrLeft);
area = insertData(wb, sheet, record , area[0],area[1],upOrLeft);
}
}
}
}
wb.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
os.flush();
os.close();
}
finally{
os.flush();
os.close();
}
return response;
}
public RecordProduces getRecordProduces(){
return RECORD_PRODUCES;
}
public Record getRecordInstance()
{
return DownExcelUtils.INSTANCE.new Record();
}
public LinkedHashMap<String,ParamType> getLinkedHashMapInstance()
{
return new LinkedHashMap<String,ParamType>();
}
public List<Record> getRecordList()
{
return new ArrayList<Record>();
}
public LinkedHashMap<String,ParamType> addParamType(LinkedHashMap<String,ParamType> linkedHashMap , String paramKey , String paramTitle ,Class<?> TypeClass){
if(linkedHashMap == null ){
linkedHashMap = getLinkedHashMapInstance();
}
linkedHashMap.put(paramKey, new ParamType(paramKey , paramTitle , TypeClass));
return linkedHashMap;
}
public LinkedHashMap<String,ParamType> addParamType(LinkedHashMap<String,ParamType> linkedHashMap , String paramKey , String paramTitle){
if(linkedHashMap == null ){
linkedHashMap = getLinkedHashMapInstance();
}
linkedHashMap.put(paramKey, new ParamType(paramKey , paramTitle));
return linkedHashMap;
}
private void insetTitle(HSSFWorkbook wb , HSSFSheet sheet ,Record record ,int height , int width , boolean upOrLeft)
{
HSSFRow titleRow = null;
if(upOrLeft){
titleRow = sheet.createRow(height);
}else{
titleRow = sheet.getRow(0);
if(titleRow == null){
titleRow = sheet.createRow(0);
}
}
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
HSSFFont font = wb.createFont();
font.setFontName("黑体");
font.setFontHeightInPoints((short) 16);//设置字体大小
style.setFont(font);
HSSFCell cell = titleRow.createCell(upOrLeft == true ? 0 : width);
cell.setCellStyle(style);
if(StringUtils.isNotEmpty(record.getTitle())){
cell.setCellValue(record.getTitle());
}
}
/**
* 导入数据到表格中
* @param wb execl文件
* @param sheet 表格
* @param row 表格行
* @param record 要导出的数据
* @param out 输出流
*/
private Integer[] insertData(HSSFWorkbook wb, HSSFSheet sheet, Record recordColection , int height , int width , boolean upOrLeft ){
HSSFDataFormat format = wb.createDataFormat();
HSSFCellStyle style = wb.createCellStyle();
Integer[] area = new Integer[2];
LinkedHashMap<String,ParamType> param = recordColection.getParam();
List<?> record = recordColection.getRecord();
String title[] = new String[param.size()];
param.keySet().toArray(title);
HSSFRow row = null;
if(upOrLeft){
row = sheet.createRow(height + 1); ///title
}else{
row = sheet.getRow(1);
if(row == null){
row = sheet.createRow(1);
}
}
for(int i = 0; i < title.length; i++){
row.createCell( (upOrLeft == true ? i : width + i) ).setCellValue(param.get(title[i]).getParamTitle());
}
for(int i = 0 ; i < record.size(); i++ ){ data
if(upOrLeft){
row = sheet.createRow( height + i+2);
}else{
row = sheet.getRow(i+2);
if(row == null){
row = sheet.createRow(i+2);
}
}
for(int j = 0; j < title.length; j++){
ParamType paramType = param.get(title[j]);
MethodVO methodVO = getObjectValue(record.get(i),paramType.getParamKey());
if(methodVO.getObj() == null){
row.createCell( upOrLeft == true ? j : width + j ).setCellValue("");
}else{
if( recordColection.getIsRealType() == null || recordColection.getIsRealType() == false){
row.createCell(upOrLeft == true ? j : width + j).setCellValue(String.valueOf(methodVO.getObj()));
}else{
row = fillRealType(row,upOrLeft == true ? j : width + j , methodVO, paramType.getTypeClass(), format, style);
}
}
}
}
if(upOrLeft){
CellRangeAddress region = new CellRangeAddress(height,height, 0,title.length-1);
sheet.addMergedRegion(region);
}else{
CellRangeAddress region = new CellRangeAddress(0,0, width, width + title.length-1);
sheet.addMergedRegion(region);
}
if(upOrLeft){
area[0] = height + record.size() + 3;
area[1] = (width + title.length + 1);
}else{
area[0] = record.size() + 3;
area[1] = (width + title.length + 1);
}
return area;
}
/**
*
* @description: 获取实体的 filed值
* @param obj
* @param filed
* @return
*/
private MethodVO getObjectValue(Object obj, String filed)
{
MethodVO result = new MethodVO();
try {
Class<? extends Object> clazz = obj.getClass();
PropertyDescriptor pd = new PropertyDescriptor(filed, clazz);
Method method = pd.getReadMethod(); //获得get方法
if (pd != null) {
result.setObj(method.invoke(obj));
result.setMethod(method);
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IntrospectionException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
return result;
}
//填充真实的类型
private HSSFRow fillRealType(HSSFRow row, int j, MethodVO methodVO , Class<?> realClass , HSSFDataFormat format,HSSFCellStyle style ){
Method method = methodVO.getMethod();
Object obj = methodVO.getObj();
Type type = method.getGenericReturnType();
if(StringUtils.isTrimEmpty(String.valueOf(obj))){
row.createCell(j).setCellValue(String.valueOf(obj));
return row;
}
try
{
if(realClass != null){
if(realClass.equals(String.class)){
row.createCell(j).setCellValue(String.valueOf(obj));
}else if(realClass.equals(Integer.class)|| realClass.equals(int.class)){
row.createCell(j).setCellValue(Integer.valueOf(String.valueOf(obj)));
}else if(realClass.equals(Double.class)||realClass.equals(double.class)){
row.createCell(j).setCellValue(Double.valueOf(String.valueOf(obj)));
}else if(realClass.equals(Float.class)|| realClass.equals(float.class)){
row.createCell(j).setCellValue( new Float(String.valueOf(obj)));
}else if(realClass.equals(Date.class)){
style.setDataFormat(format.getFormat(getDateTag(obj)));
if(type.equals(Date.class)){
row.createCell(j).setCellValue(
DateUtils.getJustDate((((Date)obj).getTime())));
row.getCell(j).setCellStyle(style);
}else{
row.createCell(j).setCellValue(
DateUtils.getDate(String.valueOf(obj),getDateSourceTag(obj)));
row.getCell(j).setCellStyle(style);
}
}else{
row.createCell(j).setCellValue(String.valueOf(obj));
}
}else{
if(type.equals(String.class)){
row.createCell(j).setCellValue(String.valueOf(obj));
}else if(type.equals(Integer.class)|| type.equals(int.class)){
row.createCell(j).setCellValue(Integer.valueOf(String.valueOf(obj)));
}else if(type.equals(Double.class)||type.equals(double.class)){
row.createCell(j).setCellValue(Double.valueOf(String.valueOf(obj)));
}else if(type.equals(Float.class)|| type.equals(float.class)){
row.createCell(j).setCellValue(Float.valueOf(String.valueOf(obj)));
}else if(type.equals(Date.class)){
style.setDataFormat(format.getFormat(getDateTag(obj)));
row.createCell(j).setCellValue(
DateUtils.getJustDate((((Date)obj).getTime())));
row.getCell(j).setCellStyle(style);
}else{
row.createCell(j).setCellValue(String.valueOf(obj));
}
}
}
catch (Exception e){
row.createCell(j);
}
return row;
}
private String getDateTag(Object obj){
if(obj.equals(Date.class)){
return "yyyy/M/d";
}else{
String tag = "yyyy/M/d";
String dateTagArr[] = String.valueOf(obj).split("-");
if(dateTagArr.length == 2){
tag = "yyyy/M";
}else if(dateTagArr.length == 1){
tag = "yyyy";
}else{
tag = "yyyy/M/d";
}
return tag;
}
}
private String getDateSourceTag(Object obj){
if(obj.equals(Date.class)){
return "yyyy-MM-dd";
}else{
String tag = "yyyy-MM-dd";
String dateTagArr[] = String.valueOf(obj).split("-");
if(dateTagArr.length == 2){
tag = "yyyy-MM";
}else if(dateTagArr.length == 1){
tag = "yyyy";
}else{
tag = "yyyy-MM-dd";
}
return tag;
}
}
private Set<String> getAllSheetName(HSSFWorkbook workbook){
Set<String> set = new HashSet<String>();
if(workbook.getNumberOfSheets() > 0 ){
for(int i= 0; i < workbook.getNumberOfSheets(); i++){
set.add(workbook.getSheetAt(i).getSheetName());
}
}
return set;
}
/**
*
* @description: 获取sheet 的名称
* @param records
* @return
*/
private String getSheetName(HSSFWorkbook wb, String sheetName){
if(StringUtils.isNotEmpty(sheetName)){
HSSFSheet sheet = wb.getSheet(sheetName);
if(sheet == null){
return sheetName;
}else{
return getDefaultSheetName(wb,sheetName);
}
}else{
return getDefaultSheetName(wb,"Sheet");
}
}
private String getDefaultSheetName(HSSFWorkbook wb,String preName){
Set<String> allName = getAllSheetName(wb);
String defaultName = "";
int i = 1;
while(true){
defaultName = preName+"副本"+(i++);
if(!allName.contains(defaultName)){break;}
}
return defaultName;
}
private class MethodVO implements Serializable
{
private static final long serialVersionUID = 1L;
private Object obj;
private Method method;
public Object getObj()
{
return obj;
}
public void setObj(Object obj)
{
this.obj = obj;
}
public Method getMethod()
{
return method;
}
public void setMethod(Method method)
{
this.method = method;
}
}
public class ParamType implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -3672552185769409063L;
String paramKey;
String paramTitle;
Class<?> TypeClass;
public ParamType(String paramKey, String paramTitle, Class<?> typeClass)
{
this.paramKey = paramKey;
this.paramTitle = paramTitle;
TypeClass = typeClass;
}
public ParamType(String paramKey, String paramTitle)
{
this.paramKey = paramKey;
this.paramTitle = paramTitle;
}
public String getParamKey()
{
return paramKey;
}
public void setParamKey(String paramKey)
{
this.paramKey = paramKey;
}
public String getParamTitle()
{
return paramTitle;
}
public void setParamTitle(String paramTitle)
{
this.paramTitle = paramTitle;
}
public Class<?> getTypeClass()
{
return TypeClass;
}
public void setTypeClass(Class<?> typeClass)
{
TypeClass = typeClass;
}
}
public class Record implements Serializable
{
private static final long serialVersionUID = 383811221104753903L;
private String title;
private String sheetName;
private Boolean isRealType; //默认是使用
private List<?> record;
private LinkedHashMap<String,ParamType> param;
public String getSheetName()
{
return sheetName;
}
public void setSheetName(String sheetName)
{
this.sheetName = sheetName;
}
public List<?> getRecord()
{
return record;
}
public void setRecord(List<?> record)
{
this.record = record;
}
public LinkedHashMap<String, ParamType> getParam()
{
return param;
}
public void setParam(LinkedHashMap<String, ParamType> param)
{
this.param = param;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public Boolean getIsRealType()
{
return isRealType;
}
public void setIsRealType(Boolean isRealType)
{
this.isRealType = isRealType;
}
}
public class RecordProduces implements Serializable
{
private static final long serialVersionUID = 383811221104753903L;
private String fileName;
private List<Record> records;
private Boolean mutilSheet; //多个 Record 时候, 是否使用 多个 sheet 表单 装载 , true 多个表单, false 单个
private Boolean alignLeft; //多个 Record 时候 , 只使用一个 sheet 表单 是从上往下排列数据还是从左往右排列数据 true 左右, false 上下
public String getFileName()
{
return fileName;
}
public void setFileName(String fileName)
{
this.fileName = fileName;
}
public List<Record> getRecords()
{
return records;
}
public void setRecords(List<Record> records)
{
this.records = records;
}
public Boolean getMutilSheet()
{
return mutilSheet;
}
public void setMutilSheet(Boolean mutilSheet)
{
this.mutilSheet = mutilSheet;
}
public Boolean getAlignLeft()
{
return alignLeft;
}
public void setAlignLeft(Boolean alignLeft)
{
this.alignLeft = alignLeft;
}
}
/**
*
* @description: 导出单个记录
* @param request
* @param response
* @param entityList 记录
* @param column 对象列描述Map
* @param title 标题
* @param fileName 文件名
*/
public static void export(HttpServletRequest request,HttpServletResponse response , List<?> entityList, LinkedHashMap<String,String> column ,String title, String fileName ){
if(!CollectionUtils.isEmpty(entityList)){
DownExcelUtils instance = DownExcelUtils.INSTANCE;
RecordProduces recordProduces = instance.getRecordProduces();
List<Record> records = instance.getRecordList();
LinkedHashMap<String,ParamType> param = new LinkedHashMap<String,ParamType>();
for (String key : column.keySet()) {
instance.addParamType(param, key, column.get(key));
}
Record record = instance.getRecordInstance();
record.setParam(param);
record.setRecord(entityList);
record.setTitle(title);
records.add(record);
recordProduces.setMutilSheet(false);
recordProduces.setFileName(fileName);
recordProduces.setRecords(records);
try
{
instance.export(response, recordProduces);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
public static void exportWithParamType(HttpServletRequest request,HttpServletResponse response , List<?> entityList, LinkedHashMap<String,ParamType> param ,String title, String fileName ){
if(!CollectionUtils.isEmpty(entityList)){
DownExcelUtils instance = DownExcelUtils.INSTANCE;
RecordProduces recordProduces = instance.getRecordProduces();
List<Record> records = instance.getRecordList();
Record record = instance.getRecordInstance();
record.setParam(param);
record.setRecord(entityList);
record.setTitle(title);
record.setIsRealType(false);
records.add(record);
recordProduces.setMutilSheet(false);
recordProduces.setFileName(fileName);
recordProduces.setRecords(records);
try
{
instance.export(response, recordProduces);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
/**
*
* @description: 装载 record
* @param entityList
* @param column
* @param title
* @return
*/
public static Record loadRecord(List<?> entityList,LinkedHashMap<String,String> column ,String title){
DownExcelUtils instance = DownExcelUtils.INSTANCE;
LinkedHashMap<String,ParamType> param = new LinkedHashMap<String,ParamType>();
for (String key : column.keySet()) {
instance.addParamType(param, key, column.get(key));
}
Record record = instance.getRecordInstance();
record.setParam(param);
record.setRecord(entityList);
record.setTitle(title);
return record;
}
public static Record loadRecordWithParamType(List<?> entityList,LinkedHashMap<String,ParamType> param ,String title){
DownExcelUtils instance = DownExcelUtils.INSTANCE;
Record record = instance.getRecordInstance();
record.setParam(param);
record.setRecord(entityList);
record.setTitle(title);
record.setIsRealType(false);
return record;
}
}
具体使用方法:
// 对象数据集合
ArrayList<Object> list = new ArrayList<Object>();
DownExcelUtils instance = DownExcelUtils.INSTANCE;
LinkedHashMap<String,ParamType> column = new LinkedHashMap<String,ParamType>();
// orderSn --是对象的字段,“订单号” -- excle 表头的名字
// 以此类推,添加对象字段和excle表头
instance.addParamType(column, "orderSn","订单号");
instance.addParamType(column, "orderSn","订单号");
instance.addParamType(column, "orderSn","订单号");
RecordProduces recordProduces = instance.getRecordProduces();
List<Record> records = instance.getRecordList();
// 将单个list 封装成Record对象,
Record record = DownExcelUtils.loadRecordWithParamType(list, column, "excle名");
/**
* 可以添加多个list 数据一起导出
*/
//Record record = DownExcelUtils.loadRecordWithParamType(list, column, "excle名");
// 加入
records.add(record);
//records.add(record);如果多个
recordProduces.setMutilSheet(false);//多个 Record 时候, 是否使用 多个 sheet 表单 装载 , true 多个表单, false 单个
// recordProduces.setAlignLeft(true);多个 Record 时候 , 只使用一个 sheet 表单 是从
//上往下排列数据还是从左往右排列数据 true 左右, false 上下
recordProduces.setFileName("excle名");
recordProduces.setRecords(records);
try
{
// 导出
instance.export(response, recordProduces);
}
catch (Exception e)
{
e.printStackTrace();
}