```
导入包pom.xml
<!-- 导出excel依赖包 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
package com.sports.core.util.ExportExcel;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Description: 导出Excel
*
* @author 作者:Mirai
* @date 创建时间:2017年4月15日 下午8:00:22
*/
public class ExportExcel<T> {
/**
* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
*
* @param title
* 表格标题名(如 XXX.xls)
* @param headers
* 表格属性列名数组
* @param headersname
* 表格属性数据集合列明数字
* @param dataset
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
* @param response
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void exportExcel(String title, String[] headers,
String[] headersname, Collection<T> dataset, String pattern,
HttpServletResponse response) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet1 = workbook.createSheet(title);
sheet1.autoSizeColumn(100);
// 创建一行,在页sheet上
Row row = sheet1.createRow((short) 0);
// 声明一个画图的顶级管理器
// HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
/*
* // 定义注释的大小和位置,详见文档 HSSFComment comment = patriarch.createComment(new
* HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
*/
HSSFFont headerFont = (HSSFFont) workbook.createFont(); // 创建字体样式
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
headerFont.setFontName("Times New Roman"); // 设置字体类型
headerFont.setFontHeightInPoints((short) 8); // 设置字体大小
HSSFCellStyle headerStyle = (HSSFCellStyle) workbook.createCellStyle();// 创建标题样式
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置水平居中
headerStyle.setFont(headerFont); // 为标题样式设置字体样式
HSSFFont cell_Font = (HSSFFont) workbook.createFont(); // 设置字体样式
cell_Font.setFontName("宋体");
cell_Font.setFontHeightInPoints((short) 8);
HSSFCellStyle cell_Style = (HSSFCellStyle) workbook.createCellStyle();// 设置单元格样式
cell_Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell_Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直对齐居中
cell_Style.setWrapText(true); // 设置为自动换行
cell_Style.setFont(cell_Font);
cell_Style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cell_Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
cell_Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
cell_Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
int[] int_number = new int[headers.length];
// 列设置标题
for (int i = 0; i < headers.length; i++) {
Cell cell = row.createCell((short) i); // 创建列
cell.setCellStyle(headerStyle);
cell.setCellValue(headers[i]);
int_number[i] = getWordCount(headers[i]) * 2;
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet1.createRow((short) index); // 创建行
T t = (T) it.next();// 获取集合信息
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < headersname.length; i++) {
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
if (headersname[i] == fieldName) {
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if (value == null) {//
textValue = "";
} else if (value instanceof Boolean) {// Boolean类型
boolean bValue = (Boolean) value;
textValue = "true";
if (!bValue) {
textValue = "false";
}
} else if (value instanceof Date) {// date类型
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(
pattern);
textValue = sdf.format(date);
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据
if (textValue != null) {
Cell cell = row.createCell((short) i); // 创建列
cell.setCellStyle(cell_Style);
cell.setCellValue(textValue);
if (int_number[i] < getWordCount(textValue)) {
int_number[i] = getWordCount(textValue);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
// 清理资源
}
}
}
}
}
for (int i = 0; i < int_number.length; i++) {
sheet1.setColumnWidth(i, int_number[i] * 256);
}
try {
//输出excel文件
response.reset();
OutputStream os = response.getOutputStream();//创建流
//下载中文名乱码解决办法
response.setHeader("Content-Disposition", "attachment;fileName="+ new String(title.getBytes("gbk"),"iso-8859-1"));
response.setContentType("application/msexcel");
workbook.write(os);// 把上面创建的工作簿输出到文件流中
os.close();//关闭流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 按字节获得字符串长度的两种方法 正则表达式
*
* @param s
* 字符串
* @return 字符串字节数
*/
public static int getWordCount(String s) {
// 将字符串中所有的非标准字符(双字节字符)替换成两个标准字符(**,或其他的也可以)。这样就可以直接例用length方法获得字符串的字节长度了
s = s.replaceAll("[^\\x00-\\xff]", "**");
int length = s.length();
return length;
}
}
Controller调用
@RequestMapping("/writeExcel")
public Object writeExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
title = "订单信息.xls"
List<IndentVo> list = indentService.vagueFind("条件");//查询数据
ExportExcel<IndentVo> ex = new ExportExcel<IndentVo>();
String title = DateUtil.getStringDateTime("yyyyMMddHHmmss", new Date()) + "客户订单.xls";
String[] headers = {"订单号","产品名称","卖家","买家","订单状态","单价","数量","总额","下单时间"};
String[] headersname ={"indentnumbe","productname","businessname","wcusername","indentstate","price","number","amountpayable","createtime"};
ex.exportExcel(title, headers, headersname, list, "yyyy-MM-dd HH:mm:ss", response());
}
导入包pom.xml
<!-- 导出excel依赖包 -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
package com.sports.core.util.ExportExcel;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
/**
* Description: 导出Excel
*
* @author 作者:Mirai
* @date 创建时间:2017年4月15日 下午8:00:22
*/
public class ExportExcel<T> {
/**
* 这是一个通用的方法,利用了JAVA的反射机制,可以将放置在JAVA集合中并且符号一定条件的数据以EXCEL 的形式输出到指定IO设备上
*
* @param title
* 表格标题名(如 XXX.xls)
* @param headers
* 表格属性列名数组
* @param headersname
* 表格属性数据集合列明数字
* @param dataset
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyy-MM-dd"
* @param response
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public void exportExcel(String title, String[] headers,
String[] headersname, Collection<T> dataset, String pattern,
HttpServletResponse response) {
// 声明一个工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成一个表格
HSSFSheet sheet1 = workbook.createSheet(title);
sheet1.autoSizeColumn(100);
// 创建一行,在页sheet上
Row row = sheet1.createRow((short) 0);
// 声明一个画图的顶级管理器
// HSSFPatriarch patriarch = sheet1.createDrawingPatriarch();
/*
* // 定义注释的大小和位置,详见文档 HSSFComment comment = patriarch.createComment(new
* HSSFClientAnchor(0, 0, 0, 0, (short) 4, 2, (short) 6, 5));
*/
HSSFFont headerFont = (HSSFFont) workbook.createFont(); // 创建字体样式
headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 字体加粗
headerFont.setFontName("Times New Roman"); // 设置字体类型
headerFont.setFontHeightInPoints((short) 8); // 设置字体大小
HSSFCellStyle headerStyle = (HSSFCellStyle) workbook.createCellStyle();// 创建标题样式
headerStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 设置垂直居中
headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置水平居中
headerStyle.setFont(headerFont); // 为标题样式设置字体样式
HSSFFont cell_Font = (HSSFFont) workbook.createFont(); // 设置字体样式
cell_Font.setFontName("宋体");
cell_Font.setFontHeightInPoints((short) 8);
HSSFCellStyle cell_Style = (HSSFCellStyle) workbook.createCellStyle();// 设置单元格样式
cell_Style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
cell_Style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直对齐居中
cell_Style.setWrapText(true); // 设置为自动换行
cell_Style.setFont(cell_Font);
cell_Style.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 下边框
cell_Style.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 左边框
cell_Style.setBorderTop(HSSFCellStyle.BORDER_THIN);// 上边框
cell_Style.setBorderRight(HSSFCellStyle.BORDER_THIN);// 右边框
int[] int_number = new int[headers.length];
// 列设置标题
for (int i = 0; i < headers.length; i++) {
Cell cell = row.createCell((short) i); // 创建列
cell.setCellStyle(headerStyle);
cell.setCellValue(headers[i]);
int_number[i] = getWordCount(headers[i]) * 2;
}
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
while (it.hasNext()) {
index++;
row = sheet1.createRow((short) index); // 创建行
T t = (T) it.next();// 获取集合信息
// 利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for (int i = 0; i < headersname.length; i++) {
for (int j = 0; j < fields.length; j++) {
Field field = fields[j];
String fieldName = field.getName();
String getMethodName = "get"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
if (headersname[i] == fieldName) {
try {
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
String textValue = null;
if (value == null) {//
textValue = "";
} else if (value instanceof Boolean) {// Boolean类型
boolean bValue = (Boolean) value;
textValue = "true";
if (!bValue) {
textValue = "false";
}
} else if (value instanceof Date) {// date类型
Date date = (Date) value;
SimpleDateFormat sdf = new SimpleDateFormat(
pattern);
textValue = sdf.format(date);
} else if (value instanceof byte[]) {
//图片类型
textValue = null;
// 其它数据类型都当作字符串简单处理
textValue = value.toString();
}
// 如果不是图片数据
if (textValue != null) {
Cell cell = row.createCell((short) i); // 创建列
cell.setCellStyle(cell_Style);
cell.setCellValue(textValue);
if (int_number[i] < getWordCount(textValue)) {
int_number[i] = getWordCount(textValue);
}
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
// 清理资源
}
}
}
}
}
for (int i = 0; i < int_number.length; i++) {
sheet1.setColumnWidth(i, int_number[i] * 256);
}
try {
//输出excel文件
response.reset();
OutputStream os = response.getOutputStream();//创建流
//下载中文名乱码解决办法
response.setHeader("Content-Disposition", "attachment;fileName="+ new String(title.getBytes("gbk"),"iso-8859-1"));
response.setContentType("application/msexcel");
workbook.write(os);// 把上面创建的工作簿输出到文件流中
os.close();//关闭流
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 按字节获得字符串长度的两种方法 正则表达式
*
* @param s
* 字符串
* @return 字符串字节数
*/
public static int getWordCount(String s) {
// 将字符串中所有的非标准字符(双字节字符)替换成两个标准字符(**,或其他的也可以)。这样就可以直接例用length方法获得字符串的字节长度了
s = s.replaceAll("[^\\x00-\\xff]", "**");
int length = s.length();
return length;
}
}
Controller调用
@RequestMapping("/writeExcel")
public Object writeExcel(HttpServletRequest request, HttpServletResponse response) throws IOException{
title = "订单信息.xls"
List<IndentVo> list = indentService.vagueFind("条件");//查询数据
ExportExcel<IndentVo> ex = new ExportExcel<IndentVo>();
String title = DateUtil.getStringDateTime("yyyyMMddHHmmss", new Date()) + "客户订单.xls";
String[] headers = {"订单号","产品名称","卖家","买家","订单状态","单价","数量","总额","下单时间"};
String[] headersname ={"indentnumbe","productname","businessname","wcusername","indentstate","price","number","amountpayable","createtime"};
ex.exportExcel(title, headers, headersname, list, "yyyy-MM-dd HH:mm:ss", response());
}