导出Excel工具类
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook; /**
* Description: 导出工具类
* All Rights Reserved.
*/
public class ExcelExprot {
@SuppressWarnings("unchecked")
public void exportExcel(HttpServletResponse response, String fileName,
ExcelModel... excelModels) {
// 输出流
OutputStream os = null;
// excel文件
Workbook wb = null;
// excel工作表
Sheet st; try {
os = response.getOutputStream();
if ((fileName.trim().substring(fileName.indexOf(".")))
.equals(".xlsx"))
wb = new XSSFWorkbook();
else
wb = new HSSFWorkbook();
for (ExcelModel excelModel : excelModels) {
if (excelModel.getSheetName() != null
&& excelModel.getSheetName().trim().length() != 0) {
st = wb.createSheet(excelModel.getSheetName());
} else {
st = wb.createSheet();
}
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
// 设置文字蓝色 且剧中
CellStyle styleBlueFontNotWrap = wb.createCellStyle();
styleBlueFontNotWrap
.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
styleBlueFontNotWrap.setFont(font);
styleBlueFontNotWrap.setAlignment(CellStyle.VERTICAL_CENTER);
styleBlueFontNotWrap.setAlignment(CellStyle.ALIGN_CENTER);
styleBlueFontNotWrap.setWrapText(false); Boolean cbFlag = excelModel.getCallBack() != null;
Row row = null;
Cell cell = null;
int rowcursor = 0;
int columncursor = 0;
row = st.createRow(rowcursor);
row.setHeight((short) 500);
for (int i = 0; i < excelModel.getHeaders().length; i++) {
st.setColumnWidth(i, 7000);
columncursor = i;
String value = excelModel.getHeaders()[i];
cell = row.createCell(columncursor);
cell.setCellValue(value);
cell.setCellStyle(styleBlueFontNotWrap);
if (cbFlag) {
excelModel.getCallBack().execute(rowcursor,
columncursor, cell, value);
}
}
rowcursor++;
List<?> datas = excelModel.getDatas();
if (datas != null && datas.size() > 0) {
while (true) {
if (datas.size() + 1 == rowcursor) {
break;
}
row = st.createRow(rowcursor);
Class<?> cls = excelModel.getDataCls();
if (cls.getName().equals("java.util.Map")) {
Map<String, Object> map = (Map<String, Object>) datas
.get(rowcursor - 1);
for (int i = 0; i < excelModel.getBodys().length; i++) {
columncursor = i;
Object value = map
.get(excelModel.getBodys()[i]);
createCell(excelModel, cbFlag, row, rowcursor,
columncursor, value);
}
} else {
Object obj = datas.get(rowcursor - 1);
String[] bodys = excelModel.getBodys();
for (int i = 0; i < bodys.length; i++) {
columncursor = i;
String methodName = "get"
+ bodys[i].substring(0, 1)
.toUpperCase()
+ bodys[i].substring(1);
Method met = cls.getMethod(methodName);
Object value = met.invoke(obj);
createCell(excelModel, cbFlag, row, rowcursor,
columncursor, value);
}
}
rowcursor++;
}
}
} response.setContentType("application/msexcel;charset=UTF-8");
// 定义输出类型
fileName = new String(fileName.getBytes("gb2312"), "ISO-8859-1");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName);
wb.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null)
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
} /**
* <p>Title: exportExcelExtend </p>
* Description: 合并单元格 * @param response
* @param fileName
* @param excelModels
*/
@SuppressWarnings("unchecked")
public void exportExcelExtends(HttpServletResponse response,String fileName, String[] header1,String[] header2,
ExcelModel... excelModels) {
// 输出流
OutputStream os = null;
// excel文件
Workbook wb = null;
// excel工作表
Sheet st; try {
os = response.getOutputStream();
if ((fileName.trim().substring(fileName.indexOf(".")))
.equals(".xlsx"))
wb = new XSSFWorkbook();
else
wb = new HSSFWorkbook();
for (ExcelModel excelModel : excelModels) {
if (excelModel.getSheetName() != null
&& excelModel.getSheetName().trim().length() != 0) {
st = wb.createSheet(excelModel.getSheetName());
} else {
st = wb.createSheet();
}
Font font = wb.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD);
// 设置文字蓝色 且剧中
CellStyle styleBlueFontNotWrap = wb.createCellStyle();
styleBlueFontNotWrap
.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index);
styleBlueFontNotWrap.setFont(font);
styleBlueFontNotWrap.setAlignment(CellStyle.VERTICAL_CENTER);
styleBlueFontNotWrap.setAlignment(CellStyle.ALIGN_CENTER);
styleBlueFontNotWrap.setWrapText(false); Boolean cbFlag = excelModel.getCallBack() != null;
Row row = null;
Cell cell = null;
int rowcursor = 0;
int columncursor = 0; st.addMergedRegion(new CellRangeAddress(0,1,0,0));
st.addMergedRegion(new CellRangeAddress(0,1,1,1));
st.addMergedRegion(new CellRangeAddress(0,0,2,5));
st.addMergedRegion(new CellRangeAddress(0,0,6,9)); row = st.createRow(rowcursor);
row.setHeight((short) 400);
for (int i = 0; i < header1.length; i++) {
st.setColumnWidth(i, 7000);
columncursor = i;
String value = header1[i];
cell = row.createCell(columncursor);
cell.setCellValue(value);
cell.setCellStyle(styleBlueFontNotWrap);
if (cbFlag) {
excelModel.getCallBack().execute(rowcursor,
columncursor, cell, value);
}
}
rowcursor++;
row = st.createRow(rowcursor);
row.setHeight((short) 400);
for (int i = 1; i < header2.length; i++) {
st.setColumnWidth(i, 7000);
columncursor = i;
String value = header2[i];
cell = row.createCell(columncursor);
cell.setCellValue(value);
cell.setCellStyle(styleBlueFontNotWrap);
if (cbFlag) {
excelModel.getCallBack().execute(rowcursor,
columncursor, cell, value);
}
}
rowcursor++;
List<?> datas = excelModel.getDatas();
if (datas != null && datas.size() > 0) {
while (true) {
if (datas.size() + 2 == rowcursor) {
break;
}
row = st.createRow(rowcursor);
Class<?> cls = excelModel.getDataCls();
if (cls.getName().equals("java.util.Map")) {
Map<String, Object> map = (Map<String, Object>) datas
.get(rowcursor - 2);
for (int i = 0; i < excelModel.getBodys().length; i++) {
columncursor = i;
Object value = map
.get(excelModel.getBodys()[i]);
createCell(excelModel, cbFlag, row, rowcursor,
columncursor, value);
}
} else {
Object obj = datas.get(rowcursor - 2);
String[] bodys = excelModel.getBodys();
for (int i = 0; i < bodys.length; i++) {
columncursor = i;
String methodName = "get"
+ bodys[i].substring(0, 1)
.toUpperCase()
+ bodys[i].substring(1);
Method met = cls.getMethod(methodName);
Object value = met.invoke(obj);
createCell(excelModel, cbFlag, row, rowcursor,
columncursor, value);
}
}
rowcursor++;
}
}
}
response.setContentType("application/msexcel;charset=UTF-8");
// 定义输出类型
fileName = new String(fileName.getBytes("gb2312"), "ISO8859-1");
response.setHeader("Content-disposition", "attachment; filename="
+ fileName);
wb.write(os);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (os != null)
os.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
} private void createCell(ExcelModel excelModel, Boolean cbFlag, Row row,
int rowcursor, int columncursor, Object value) {
if (value != null) {
Cell cell = row.createCell(columncursor);
try {
if (value.getClass().getName().equals("java.util.Date")) {
if (excelModel.getDateFormat() != null) {
SimpleDateFormat df = new SimpleDateFormat(
excelModel.getDateFormat());
cell.setCellValue(df.format((Date) value));
} else {
cell.setCellValue((Date) value);
}
} else if (value.getClass().getName().equals("boolean")
|| value.getClass().getName()
.equals("java.lang.Boolean")) {
cell.setCellValue(Double.valueOf(value.toString()));
} else {
cell.setCellValue(value.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
if (cbFlag) {
excelModel.getCallBack().execute(rowcursor, columncursor, cell,
value);
}
}
}
}
import org.apache.poi.ss.usermodel.Cell; /**
* Description: excel的回调工具类
* All Rights Reserved.
*/
public interface ExcelCallBack {
/**
* Description: 可根据行号 或者列号来操作单元格的数据或者样式 * @param row
* @param column
* @param cell
* @param value
*/
public void execute(int row, int column, Cell cell, Object value);
}
import java.util.List; /**
* Description: excelModel
* All Rights Reserved.
*/
public class ExcelModel {
// sheet 页名称
private String sheetName;
// 头名称数组
private String[] headers;
// 数据顺序 实体类属性或者map的key
private String[] bodys;
// 数据集合
private List<?> datas;
// 数据类型 map 或者实体类
private Class<?> dataCls;
// 回调函数 可以修改对应cell的值 也可以添加样式等
private ExcelCallBack callBack;
// 日期格式
private String dateFormat; public String getSheetName() {
return sheetName;
} public void setSheetName(String sheetName) {
this.sheetName = sheetName;
} public String[] getHeaders() {
return headers;
} public void setHeaders(String[] headers) {
this.headers = headers;
} public void setHeader(String... headers) {
this.headers = headers;
} public String[] getBodys() {
return bodys;
} public void setBodys(String[] bodys) {
this.bodys = bodys;
} public void setBody(String... bodys) {
this.bodys = bodys;
} public ExcelCallBack getCallBack() {
return callBack;
} public void setCallBack(ExcelCallBack callBack) {
this.callBack = callBack;
} public List<?> getDatas() {
return datas;
} public void setDatas(List<?> datas) {
this.datas = datas;
} public Class<?> getDataCls() {
return dataCls;
} public void setDataCls(Class<?> dataCls) {
this.dataCls = dataCls;
} public String getDateFormat() {
return dateFormat;
} public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
}
private String methodName(Result result, String respResult,List<Object> list) {
String period =new SimpleDateFormat("yyyy-MM-dd").format(new Date());
String excelName = null;
ExcelExprot excelExprot = new ExcelExprot();
// 构建参数
ExcelModel excelModel = new ExcelModel();
excelName = "";
excelModel.setSheetName("");
excelModel.setHeader("", "", "", "","");
excelModel.setBody("", "", "", "","");
excelModel.setDatas(list);
excelModel.setDataCls(Object.class);
try {
excelModel.setCallBack(new ExcelCallBack() {
@Override
// 可根据行号 或者列号来操作单元格的数据或者样式
public void execute(int row, int column, Cell cell, Object value) {
Class<?> cls = value.getClass();
if (cls.equals(java.util.Date.class) || cls.equals(java.sql.Timestamp.class)) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell.setCellValue(sdf.format((Date) value));
}else {
cell.setCellValue(value.toString());
}
}
});
// 调用导出方法 response测试传入null
excelExprot.exportExcel(response, excelName + period + ".xlsx", excelModel);
} catch (Exception e) {
log.error(e.getMessage(),e);
respResult = result.error(e.getMessage());
}
return respResult;
}
导出Excel工具类的更多相关文章
- 导入导出Excel工具类ExcelUtil
前言 前段时间做的分布式集成平台项目中,许多模块都用到了导入导出Excel的功能,于是决定封装一个ExcelUtil类,专门用来处理Excel的导入和导出 本项目的持久化层用的是JPA(底层用hibe ...
- javaEE开发之导出excel工具类
web开发中,一个系统的普通需求也包含导出excel,一般採用POI做统计报表导出excel. 导出excel工具类: import java.io.FileOutputStream; import ...
- Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类
Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...
- java导出excel工具类
java导出excel须要使用HSSFWorkbook这个类,须要导入poi-3.6-20091214.jar 工具类调用例如以下: package com.qlwb.business.util; i ...
- Java XSSF 导出excel 工具类
参数解释: title:导出excel标题.headers 导出到excel显示的列头. columns 对应数据库字段 .list 导出数据1.pox中添加依赖 <dependency> ...
- 使用POI导出EXCEL工具类并解决导出数据量大的问题
POI导出工具类 工作中常常会遇到一些图表需要导出的功能,在这里自己写了一个工具类方便以后使用(使用POI实现). 项目依赖 <dependency> <groupId>org ...
- JXL导出Excel工具类
将Excel中的数据读取到List<Map<String, Object>>集合中 package com.mvc.util; import java.io.File; ...
- NPOI导入导出Excel工具类
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Ref ...
- 关于Excel导入导出POI工具类
import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import ...
随机推荐
- Neject 在MVC框架中使用
Neject 开始是用3.3.0.0,不能自动生成NinjectWebCommon文件,测试了很久发现,是版本的问题 ,后来用Nuget卸载后,重新下了Ninject,Ninject.Web.Comm ...
- eclipse 安装MyBatis插件 -- 官网直接拖动“安装”
拖动“安装” http://marketplace.eclipse.org/marketplace-client-intro?mpc_install=2947754
- Python常用高级函数
一 .匿名函数 有些时候,我们不需要显式的定义函数,可以使用匿名函数临时快速定义函数. lambda x: x * x 关键字lambda表示匿名函数,冒号前面的x表示函数的参数,多个参数用','隔开 ...
- upload三种上传方式(上)---Servlet---post---commons-fileupload.1.2.1.jar方式请求上传文件
上传前进行的配置选项: 1.在下方的Servers中,右键你的tomcat--open,选中下面两个配置. 第一个:Serve modules without publishing 作用:tomcat ...
- Zabbix11.3 Zabbix SNMP 常用OID列表
点击获取CISCO设备OID 系统参数(1.3.6.1.2.1.1) OID 描述 备注 请求方式 .1.3.6.1.2.1.1.1.0 获取系统基本信息 SysDesc GET .1.3.6.1.2 ...
- zabbix3.x添加华为(93069306)网络设备详解
转载自:https://www.cnblogs.com/yinzhengjie/p/6768006.html 前言: 欢迎加入:高级运维工程师之路 598432640 相信大家在看我的文章之前,也看过 ...
- 7款不错的 CI/CD工具
时至今日,越来越多的工程团队开始实行敏捷开发,借以推动更短.更快的发布周期.而代码库的增长与更高的生产构建频率,也带动持续集成与持续部署/交付工具快速兴起.如果您有意提升发布频率,或者是不太清楚哪些工 ...
- 李清华201772020113《面向对象程序设计(java)》第十一周学习总结
实验十一 集合 实验时间 2018-11-8 1.实验目的与要求 (1) 掌握Vetor.Stack.Hashtable三个类的用途及常用API: (2) 了解java集合框架体系组成: (3) ...
- oracle 查看处理锁表
--查出sid,serial#select b.username,b.sid,b.serial#,logon_time from v$locked_object a,v$session b where ...
- 超简单(两步)-微信怎么实现打开外部浏览器,下载app,打开网页URL
现在微信渠道可以说是拉新最快的渠道,因为微信具备强裂变性.但是目前微信对第三方下载链接的拦截是越来越严格了,那么想要在微信内肆无忌惮地推广链接就需要用到微信跳转浏览器的接口,那如何获取该接口呢? ...