导出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 ...
随机推荐
- 码云Gitee上新建项目教程
1.在浏览器访问,https://gitee.com/: 2.使用用户名.密码登录: 3.在左下角显示当前用户的项目,点击“+”号,创建项目: 4.填写项目的相关信息,项目名称要和本地要上传的项目名称 ...
- C6.cpp
可以将 一个array对象赋给另一个对象 对于下标值出现负数的情况下可以解释为在头指针的位置处向前移动对应的字节 可以使用vector.at(n_elem)来获取元素等价于vector[n_elem] ...
- 学习Xen
先找到两个大佬博客 进行学习 http://www.cnblogs.com/BloodAndBone/archive/2010/11/02/1866907.html https://www.cnblo ...
- Spring获取URL相关信息
获取请求的URL:request.getRequestURL().toString(); 获取上下文名称(项目名称):request.getContextPath()
- Exp6 信息搜集与漏洞扫描 20164313 杜桂鑫
1.实践目标 掌握信息搜集的最基础技能与常用工具的使用方法. 2.实践内容 (1)各种搜索技巧的应用 1.使用搜索引擎 在百度搜索栏内输入 site:com filetype:doc 北京电子科技学院 ...
- LeetCode 94. Binary Tree Inorder Traversal 二叉树的中序遍历 C++
Given a binary tree, return the inorder traversal of its nodes' values. Example: Input: [,,] \ / Out ...
- 06 Jquery 基础
前端学习之jquery: jQuery:一个库 Jquery的基础语法: $(selector).action() 基本选择器: <script> //基本选择器 //$("*& ...
- 5. Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
解决方案,见 https://www.jianshu.com/p/836d455663da
- java序列化和反序列化中的serialVersionUID有啥用
1.什么是序列化和反序列化 序列化就是将java对象转成字节序列的过程:反序列化就是将字节序列转成java对象的过程. java中,序列化的目的一种是需要将对象保存到硬盘上,一种是对象需要在网络中传 ...
- 关于Vue单页面实现微信分享的Bug
// 问题描述在微信中分享到朋友圈或好友时,分享出去的路由被破坏,打开分享的链接,路由中的“#”会被去掉并追加?from= & Timeline= 之类的后缀参数,这就造成了分享出去的链接只能 ...