package com.pangding.web.order.util;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.xssf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.lang.reflect.Field;
/**
* @author Shallow
* @date 2019/7/1 15:35
* @description 导出Excel表格
*/
public class ExcelUtil<T> {
private final static Pattern PATTERN = Pattern.compile("^//d+(//.//d+)?$");
public void exportExcel(String fileName, String title, String[] headers, Collection<T> dataset, HttpServletResponse response) {
try {
response.setContentType("application/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(fileName, "UTF-8") + ".xls");
exportExcel2007(title, headers, dataset, response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void exportExcel2007(String title, String[] headers, Collection<T> dataset, OutputStream out) {
// 声明一个工作薄
XSSFWorkbook workbook = new XSSFWorkbook();
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
XSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(new XSSFColor(java.awt.Color.gray));
style.setFillPattern(XSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(XSSFCellStyle.BORDER_THIN);
style.setBorderLeft(XSSFCellStyle.BORDER_THIN);
style.setBorderRight(XSSFCellStyle.BORDER_THIN);
style.setBorderTop(XSSFCellStyle.BORDER_THIN);
style.setAlignment(XSSFCellStyle.ALIGN_CENTER);
// 生成一个字体
XSSFFont font = workbook.createFont();
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
font.setFontName("宋体");
font.setColor(new XSSFColor(java.awt.Color.BLACK));
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
style.setFont(font);
// 产生表格标题行
XSSFRow row = sheet.createRow(0);
XSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
style.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
style.setVerticalAlignment(XSSFCellStyle.VERTICAL_CENTER);
// 生成另一个字体
XSSFFont font2 = workbook.createFont();
font2.setBoldweight(XSSFFont.BOLDWEIGHT_NORMAL);
// 把字体应用到当前的样式
style.setFont(font2);
// 遍历集合数据,产生数据行
Iterator<T> it = dataset.iterator();
int index = 0;
T t;
Field[] fields1;
Field[] fields;
Field field;
XSSFRichTextString richString;
Matcher matcher;
String fieldName;
String getMethodName;
XSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = it.next();
// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
fields1 = t.getClass().getDeclaredFields();
if(t.getClass().getSuperclass() != null){
Field[] superFields = t.getClass().getSuperclass().getDeclaredFields();
List list = new ArrayList(Arrays.asList(fields1));
list.addAll(Arrays.asList(superFields));
Field[] fields2 = new Field[list.size()];
list.toArray(fields2);
fields = fields2;
}else {
fields=fields1;
}
int j = 0;
for (int i = 0; i < fields.length; i++) {
field = fields[i];
fieldName = field.getName();
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName);
value = getMethod.invoke(t);
if(value == null){
continue;
}
// 判断值的类型后进行强制类型转换
textValue = null;
cell = row.createCell(j);
j++;
cell.setCellStyle(style);
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf(value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf(value);
cell.setCellValue(textValue);
} else if (value instanceof Long) {
cell.setCellValue((Long) value);
}
if (value instanceof Boolean) {
textValue = "是";
if (!(Boolean) value) {
textValue = "否";
}
} else if (value instanceof Date) {
textValue = sdf.format((Date) value);
} else {
// 其它数据类型都当作字符串简单处理
if (value != null) {
textValue = value.toString();
}
}
if (textValue != null) {
matcher = PATTERN.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} catch (SecurityException | NoSuchMethodException | IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
}
}
try {
workbook.write(out);
} catch (IOException e) {
e.printStackTrace();
}
}
}