package com.hanboard.educloud.util;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.Color;
import java.io.IOException;
import java.io.OutputStream;
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 java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author ZY
* @date 2018/11/6
* @copyright Hanboard
* Created by ZY on 2018/11/6.
* xxx-xxxxx处理接口
*/
public class ExportUtils {
private final static Logger logger = LoggerFactory.getLogger(ExportUtils.class);
/**
*2007 版本以上 最大支持1048576行
*/
public final static String EXCEl_FILE_2007 = "2007";
/**
* 2003 版本 最大支持65536 行
*/
public final static String EXCEL_FILE_2003 = "2003";
public static void exportExcel(String title, String[] headers, String[] fields, Collection dataset,
HttpServletResponse response, String version) {
response.setContentType("application/octet-stream");
ServletOutputStream out=null;
//转码防止乱码
try {
response.addHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gb2312"), "ISO8859-1") + ".xlsx");
out = response.getOutputStream();
}catch (Exception e){
logger.error("导出excelc出错:{}",e);
return ;
}
if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
exportExcel2003(title, headers, fields, dataset, out, "yyyy-MM-dd HH:mm:ss",null,false);
}else{
exportExcel2007(title, headers, fields,dataset, out, "yyyy-MM-dd HH:mm:ss",null,false);
}
}
/**
*
* 导出带有头部标题行的Excel
* 时间格式默认:yyyy-MM-dd hh:mm:ss
*
*
* @param title 表格标题
* @param headers 头部标题集合
* @param dataset 数据集合
* @param out 输出流
* @param version 2003 或者 2007,不传时默认生成2003版本
*/
public static void exportExcel(String title, String[] headers, String[] fields, Collection dataset,
OutputStream out, String version) {
if(StringUtils.isBlank(version) || EXCEL_FILE_2003.equals(version.trim())){
exportExcel2003(title, headers, fields, dataset, out, "yyyy-MM-dd HH:mm:ss",null,false);
}else{
exportExcel2007(title, headers, fields,dataset, out, "yyyy-MM-dd HH:mm:ss",null,false);
}
}
/**
*
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中
* 此版本生成2007以上版本的文件 (文件后缀:xlsx)
*
*
* @param title
* 表格标题名
* @param headers
* 表格头部标题集合
* @param dataset
* 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void exportExcel2007(String title, String[] headers, String[] fields,
Collection dataset, OutputStream out, String pattern, XSSFWorkbook workbook, Boolean isMoreSheet) {
try {
// 不是多个,声明一个工作薄
if(!isMoreSheet){
workbook = new XSSFWorkbook();
}
// 生成一个表格
XSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
XSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(new XSSFColor(Color.CYAN));
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
// 生成一个字体
XSSFFont font = workbook.createFont();
font.setBold(true);
font.setFontName("宋体");
font.setColor(new XSSFColor(java.awt.Color.BLACK));
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
XSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(new XSSFColor(java.awt.Color.WHITE));
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成另一个字体
XSSFFont font2 = workbook.createFont();
font2.setBold(true);
// 把字体应用到当前的样式
style2.setFont(font2);
//在sheet里增加合并单元格
int length = headers.length;
CellRangeAddress cra=new CellRangeAddress(0, 0,0, length);
sheet.addMergedRegion(cra);
XSSFRow rowtitle = sheet.createRow(0); //创建第一行(title)
rowtitle.setHeight ((short)(6*100));//设置高度
//为标题设置样式(合并单元格)
XSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(HorizontalAlignment.CENTER);//字体剧中
XSSFFont titleFont = workbook.createFont();//字体设置
titleFont.setBold(true);//粗体显示
titleFont.setFontHeightInPoints((short) 20);
titleStyle.setFont(titleFont);//选择需要用到的字体格式
//为标题创建单元格(合并单元格)
Cell titleCell= rowtitle.createCell(0);
titleCell.setCellValue(title);
titleCell.setCellStyle(titleStyle);
// 产生表格标题行
XSSFRow row = sheet.createRow(1);
XSSFCell cellHeader;
cellHeader = row.createCell(0);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new XSSFRichTextString("序号"));
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i+1);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new XSSFRichTextString(headers[i]));
}
// 遍历集合数据,产生数据行
Iterator it = dataset.iterator();
int index = 1;
T t;
XSSFRichTextString richString;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher;
String fieldName;
String getMethodName;
XSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
int indexSort=0;
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
cell = row.createCell(0);
cell.setCellStyle(style2);
cell.setCellValue(++indexSort);
t = (T) it.next();
// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
for (int i = 0; i < fields.length; i++) {
cell = row.createCell(i+1);
cell.setCellStyle(style2);
fieldName =fields[i];
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[] {});
value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) 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 = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new XSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} 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();
}
}
}
//不是多个,直接输出 是多个不管
if(!isMoreSheet){
workbook.write(out);
out.close();
}
} catch (IOException e) {
logger.error("导出excelc出错:{}",e);
}
}
/**
*
* 通用Excel导出方法,利用反射机制遍历对象的所有字段,将数据写入Excel文件中
* 此方法生成2003版本的excel,文件名后缀:xls
*
*
* @param title
* 表格标题名
* @param headers
* 表格头部标题集合
* @param fields
* 参数属性
* @param dataset
* 需要显示的数据集合,集合中一定要放置符合JavaBean风格的类的对象。此方法支持的
* JavaBean属性的数据类型有基本数据类型及String,Date
* @param out
* 与输出设备关联的流对象,可以将EXCEL文档导出到本地文件或者网络中
* @param pattern
* 如果有时间数据,设定输出格式。默认为"yyyy-MM-dd hh:mm:ss"
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public static void exportExcel2003(String title, String[] headers, String[] fields,
Collection dataset, OutputStream out, String pattern, HSSFWorkbook workbook, Boolean isMoreSheet) {
try {
// 声明一个工作薄(如果是空的)
// 不是多个,声明一个工作薄
if(!isMoreSheet){
workbook = new HSSFWorkbook();
}
// 生成一个表格
HSSFSheet sheet = workbook.createSheet(title);
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth(20);
// 生成一个样式
HSSFCellStyle style = workbook.createCellStyle();
// 设置这些样式
style.setFillForegroundColor(HSSFColor.BLUE.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
style.setAlignment(HorizontalAlignment.CENTER);
// 生成一个字体
HSSFFont font = workbook.createFont();
font.setBold(true);
font.setFontName("宋体");
font.setColor(HSSFColor.WHITE.index);
font.setFontHeightInPoints((short) 11);
// 把字体应用到当前的样式
style.setFont(font);
// 生成并设置另一个样式
HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.WHITE.index);
style2.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style2.setBorderBottom(BorderStyle.THIN);
style2.setBorderLeft(BorderStyle.THIN);
style2.setBorderRight(BorderStyle.THIN);
style2.setBorderTop(BorderStyle.THIN);
style2.setAlignment(HorizontalAlignment.CENTER);
style2.setVerticalAlignment(VerticalAlignment.CENTER);
// 生成另一个字体
HSSFFont font2 = workbook.createFont();
font2.setBold(true);
// 把字体应用到当前的样式
style2.setFont(font2);
// 产生表格标题行
HSSFRow header = sheet.createRow(0);
//在sheet里增加合并单元格
int length = headers.length;
CellRangeAddress cra=new CellRangeAddress(0, 0,0, length-1);
sheet.addMergedRegion(cra);
Row rowtitle = sheet.createRow(0); //创建第一行(title)
rowtitle.setHeight ((short)(6*100));//设置高度
//为标题设置样式
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle.setAlignment(HorizontalAlignment.CENTER);//字体剧中
HSSFFont titleFont = workbook.createFont();//字体设置
titleFont.setBold(true);//粗体显示
titleFont.setFontHeightInPoints((short) 20);
titleStyle.setFont(titleFont);//选择需要用到的字体格式
//为标题创建单元格
Cell titleCell= rowtitle.createCell(0);
titleCell.setCellValue(title);
titleCell .setCellStyle(titleStyle);
HSSFRow row = sheet.createRow(1);
HSSFCell cellHeader;
for (int i = 0; i < headers.length; i++) {
cellHeader = row.createCell(i);
cellHeader.setCellStyle(style);
cellHeader.setCellValue(new HSSFRichTextString(headers[i]));
}
// 遍历集合数据,产生数据行
Iterator it = dataset.iterator();
int index = 1;
T t;
HSSFRichTextString richString;
Pattern p = Pattern.compile("^//d+(//.//d+)?$");
Matcher matcher;
String fieldName;
String getMethodName;
HSSFCell cell;
Class tCls;
Method getMethod;
Object value;
String textValue;
SimpleDateFormat sdf = new SimpleDateFormat(pattern);
while (it.hasNext()) {
index++;
row = sheet.createRow(index);
t = (T) it.next();
// 利用反射,根据JavaBean属性的先后顺序,动态调用getXxx()方法得到属性值
for (int i = 0; i < fields.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(style2);
fieldName = fields[i];
getMethodName = "get" + fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
try {
tCls = t.getClass();
getMethod = tCls.getMethod(getMethodName, new Class[] {});
value = getMethod.invoke(t, new Object[] {});
// 判断值的类型后进行强制类型转换
textValue = null;
if (value instanceof Integer) {
cell.setCellValue((Integer) value);
} else if (value instanceof Float) {
textValue = String.valueOf((Float) value);
cell.setCellValue(textValue);
} else if (value instanceof Double) {
textValue = String.valueOf((Double) 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 = p.matcher(textValue);
if (matcher.matches()) {
// 是数字当作double处理
cell.setCellValue(Double.parseDouble(textValue));
} else {
richString = new HSSFRichTextString(textValue);
cell.setCellValue(richString);
}
}
} 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 {
// 清理资源
}
}
}
//不是多个,直接输出 是多个不管
if(!isMoreSheet){
workbook.write(out);
}
} catch (IOException e) {
logger.error("坐标转百度坐标出错:{}", e);
e.printStackTrace();
}
}
}
调用controller类
@Log(operate = "sensorStatusHistory-导出数据---星座掉线统计", logType=LogMarker.OPERATION)
@ApiOperation("导出数据---星座掉线统计")
@GetMapping("/exportDiffSite")
public void exportDiffSite(@RequestParam Map filter, HttpServletResponse response) {
sensorStatusHistoryService.exportDiffSite(filter,response);
}
service类
@Override
public void exportDiffSite(Map filter, HttpServletResponse response) {
List data=getDiffSiteData(null,filter,false);
String header =getSensorName(filter)+ "星座掉线统计"+getTitle(filter);
String way = (String)filter.get("way");
String[] title = {"星座","时间","类型", "次数"};
String[] prop = {"orgName",way,"typeStr", "number"};
if("total".equals(way)){
title = new String[]{"星座", "类型", "次数"};
prop = new String[]{"orgName", "typeStr", "number"};
}
//格式化为导出数据
try {
ExportUtils.exportExcel(header, title, prop, data, response, "2007");
} catch (Exception e) {
logger.error("导出出错:{}",e);
}
}