导出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 ...
随机推荐
- Scrapy CrawlSpider源码分析
crawl.py中主要包含两个类: 1. CrawlSpider 2. Rule link_extractor:传LinkExtractor实例对象 callback:传”func_name“ cb_ ...
- Python全栈开发记录_第五篇(装饰器)
单独记录装饰器这个知识点是因为这个知识点是非常重要的,必须掌握的(代码大约150行). 了解装饰器之前要知道三个知识点 作用域,上一篇讲到过顺序是L->E->G->B 高阶函数: 满 ...
- SQL修改某个字段中某相同部分(MySQL)
格式:UPDATE 表名 SET 字段名= REPLACE( 替换前的字段值, '替换前关键字', '替换后关键字' ) WHERE 条件;比如:update t_book SET book_no ...
- vue中提交表单后如何清空
只需要在提交方法里写上this.form={brand_right:0}即可.
- Celery异步的分布式任务调度理解
什么是Celery呢? Celery是一个用Python开发的异步的分布式任务调度模块. Celery本身不包含消息服务,使用第三方消息服务,也就是Broker,来传递任务,目前支持的有Rebbimq ...
- SQLServer 2008 已成功与服务器建立连接,但是在登录前的握手期间发生错误。 (provider: SSL Provider, error: 0 - 等待的操作过时。
在用SQL Server 2008 在连接其他电脑的实例时,一直提示“已成功与服务器建立连接,但是在登录前的握手期间发生错误. (provider: SSL Provider, error: 0 - ...
- LeetCode 206. Reverse Linked List倒置链表 C++
Reverse a singly linked list. Example: Input: 1->2->3->4->5->NULL Output: 5->4-> ...
- xml模块学习
import xml.etree.ElementTree as ET tree = ET.parse("xmltest.xml") root = tree.getroot() pr ...
- K2项目开发流程
(自己的学习资料) K2项目开发流程: 1.在VS2013中设计流程,并在K2 Workspce中测试流程 首先是新建新建一个k2的Process文件..kprx后缀. 在里面创建所需要的流程.由于我 ...
- linux脚本启动应用
手动输入一些命令,启动任务会很麻烦.可以写个start.sh脚本,去执行. #!bin/sh pid=`ps -ef|grep -v grep|grep ****-1.0-SNAPSHOT.jar|a ...