excel文件下载工具分享
好久没和大家分享点东西了,今天就和大家分享一个excel文件下载工具,项目中有很多下载功能,尤其管理系统,每个菜单下都有下载功能,如果没有一个公共的工具类,就会乱套,维护起来也很吃力(不同菜单下的下载因为excel格式的不同导致写法不同),那么我们用什么方法能够使得通过一个公共的API调用+组装各自不同的参数就可以实现不同菜单下的下载功能呢?我想你也该想到了,那就是java反射机制。不多说了,我先大体说下我的代码的用法:
涉及到的几个方法:BaseInf,fillFieldAndTitle,initParamCondition,downloadTransferProList
BaseInf:该实体类封装了excel文件的第一行标题,行读取方法,转义列表,行尾统计,数据处理类,数据处理方法
fillFieldAndTitle:组装BaseInf数据
downloadTransferProList:excel文件下载的方法,读取前面组装的java反射用的数据,利用ExcelUtil中的java反射程序实现下载
自己看去吧,很简单的
具体的代码实现:
import java.lang.reflect.Method;
import java.util.Map;
/**
* 列开头信息和结尾信息
*/
public class BaseInf {
/*
* 标题
*/
private String titleName;
/*
* 行读取方法
*/
private String columMethod;
/*
* 转义列表
*/
private Map<String, String> map;
/*
* 行尾统计
*/
private String count;
/**
* 数据处理类
*/
private Class<?> clazz;
/**
* 数据处理方法
*/
private Method method;
/**
* 全成员构造方法
* @param titleName
* @param columMethod
* @param map
* @param count
* @param clazz
* @param method
*/
public BaseInf(String titleName, String columMethod, Map<String, String> map, String count, Class<?> clazz,
Method method) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.map = map;
this.count = count;
this.clazz = clazz;
this.method = method;
}
public BaseInf(String titleName, String columMethod, Class<?> clazz, Method method) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.clazz = clazz;
this.method = method;
}
public BaseInf(String titleName, String columMethod,String count, Class<?> clazz, Method method) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.clazz = clazz;
this.method = method;
this.count = count;
}
/**
* 有转义列表 有统计的构造方法
* @param titleName
* @param columMethod
* @param map
* @param count
*/
public BaseInf(String titleName, String columMethod, Map<String, String> map, String count) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.map = map;
this.count = count;
}
/**
* 有转义列表构造方法
*
* @param titleName
* 标题
* @param columMethod
* 获取方法
* @param map
* 转义列表
*/
public BaseInf(String titleName, String columMethod, Map<String, String> map) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.map = map;
this.count = null;
}
/**
* 无转义列表 有合计数据
* @param titleName 标题
* @param columMethod 读取方法列表
* @param count 合计值
*/
public BaseInf(String titleName, String columMethod, String count) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.map = null;
this.count = count;
}
/**
* 无转义列表无统计构造方法
*
* @param titleName
* 标题
* @param columMethod
* 获取方法
*/
public BaseInf(String titleName, String columMethod) {
super();
this.titleName = titleName;
this.columMethod = columMethod;
this.map = null;
this.count = null;
}
public String getTitleName() {
return titleName;
}
public String getColumMethod() {
return columMethod;
}
public Map<String, String> getMap() {
return map;
}
public String getCount() {
return count;
}
public Class<?> getClazz() {
return clazz;
}
public Method getMethod() {
return method;
}
}
/**
* 下载接口
*/
public ActionForward downloadTransferProList(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
TtransferParam transferParam = new TtransferParam();
List<TtransferInfo> listinfo = null;
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
String startAppTime = sdf2.format(new Date());
// 开始时间
String fileName = "excel文件名称" + startAppTime;// 文件名称
try {
/*
* 初始化查询条件参数
*/
transferParam = transferService.initParamCondition(request);
/*
* 根据查询条件查询信结果
*/
listinfo = (List<TtransferInfo>) transferService.getSettleManageList(transferParam);
List<BaseInf> baseInfList = transferService.fillFieldAndTitle(listinfo);// 获取封装excel中单元格属性名和获取值的对象的集合
/*
* 调用ExcelUtil工具类实现excel下载功能
*/
if (response != null && listinfo != null) {
org.apache.poi.ss.usermodel.Workbook workbook = ExcelUtil.createWorkbook(2007, "结算提现划款查询", baseInfList,
listinfo,true);
ExcelUtil.workbook2InputStream(response, workbook, fileName, ".xls");
return null;
}
} catch (Exception e) {
String memo = "下载失败,请稍后再试 ···";
log.info("异常:{} ", memo, e);
request.setAttribute(ReturnConstant.MEMO, memo);
return mapping.findForward(ReturnConstant.ERROR);
}
return null;
}
/*封装查询参数*/
public TtransferParam initParamCondition(HttpServletRequest request) throws ParseException {
String type = request.getParameter("type");
TtransferParam transferParam = new TtransferParam();
transferParam.setMakeExcel(true);
// 参数判断
if (type != null ) {
transferParam.setType(Integer.parseInt(type));
} else {
type = "";
}
// 银行ID
if (StringUtil.isNotEmpty(bankId)) {
transferParam.setBankId(bankId);
} else {
bankId = "";
}
transferParam.setSTATE(1); // 状态
return transferParam;
}
public List<BaseInf> fillFieldAndTitle(List<TtransferInfo> list) throws NoSuchMethodException, SecurityException {
// 金额
long ableSumAmt = 0L;
// 手续费
long stlSumFee = 0L;
for (TtransferInfo tranfer : list) {
ableSumAmt += (tranfer.getT0_USEABLE_AMT() == null ? 0 : tranfer.getT0_USEABLE_AMT());
stlSumFee += (tranfer.getSTL_FEE() == null ? 0 : tranfer.getSTL_FEE());
}
List<BaseInf> baseInfList = new ArrayList<BaseInf>();
BaseInf baseInf = new BaseInf("批次号", "getID");
baseInfList.add(baseInf);
baseInf = new BaseInf("金额(元)", "getT0UserableAmt",Tools.formatAmt(ableSumAmt));
baseInfList.add(baseInf);
baseInf = new BaseInf("结算手续费(元)", "getStlFee",Tools.formatAmt(stlSumFee));
baseInfList.add(baseInf);
baseInf = new BaseInf("状态", "getSTATEStr");
baseInfList.add(baseInf);
return baseInfList;
}
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
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.IndexedColors;
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.xssf.usermodel.XSSFWorkbook;
public class ExcelUtil {
// 私有构造方法禁止new实例
private ExcelUtil() {
}
// 日志工具
// private static final Logger logger =
// LoggerFactory.getLogger(ExcelUtil.class);
// 默认日期格式
private static final String DEFAULT_DATE_PATTERN = "yyyy年MM月dd日 hh点mm分ss秒";
// 默认行高
//Columns
private static final Short DEFAULT_COLUMNS_HEIGHT = 400;
private static final Short DEFAULT_COLUMNS_WEIGHT = 1700;
/**
* 将工作表输出到浏览器中
* @param response 响应流
* @param workbook 创建完成的工作表
* @param fileName 文件名
* @param sufferNm 文件后缀名
* @throws Exception 异常
*/
public static void workbook2InputStream(HttpServletResponse response, Workbook workbook, String fileName,
String sufferNm) throws Exception {
//除去fileName的空格
fileName = fileName.replace(" ", "");
try (ServletOutputStream out = response.getOutputStream()) {
response.setCharacterEncoding("utf-8");
response.setHeader("Content-type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition",
"attachment; filename=" + new String((fileName).getBytes("gb2312"), "ISO8859-1") + sufferNm);
// 设置下载头信息
response.setContentType("application nd.ms-excel; charset=utf-8");
workbook.write(out);
out.flush();
}
}
/**
* 实体类单层嵌套 有统计栏
*/
public static Workbook createWorkbookHasCount(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
return createWorkbook(version, sheetNm, baseInfList, list, null, true);
}
/**
* 实体类单层嵌套 自定义是否有统计栏
*/
public static Workbook createWorkbook(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list, Boolean openCount)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
return createWorkbook(version, sheetNm, baseInfList, list, null, openCount);
}
/**
* 实体类单层嵌套 无统计栏
*/
public static Workbook createWorkbook(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list)
throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException,
InvocationTargetException {
return createWorkbook(version, sheetNm, baseInfList, list, null, false);
}
/**
* 创建一个数据表 实体类嵌套实体类
* @param version excel版本 2007 或者其他
* @param sheetNm sheet 名称
* @param baseInfList 数据基础信息
* @param list 数据
* @param innerMethod 实体类多层嵌套
* @return 构建完成的数据表对象
* @throws SecurityException 安全异常
* @throws NoSuchMethodException 方法没有异常
* @throws InvocationTargetException 调用异常
* @throws IllegalArgumentException 非法参数异常
* @throws IllegalAccessException 非法访问异常
* @see BaseInf
*/
public static Workbook createWorkbook(int version, String sheetNm, List<BaseInf> baseInfList, List<?> list,
String innerMethod, Boolean openCount) throws NoSuchMethodException, SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
Workbook workbook;
if (version == 2007) {
workbook = new XSSFWorkbook();
} else {
workbook = new HSSFWorkbook();
}
Sheet sheet = workbook.createSheet(isEmpty(sheetNm) ? "sheet1" : sheetNm);
// 写入标题
CellStyle titleStyle = titleStyle(workbook);
// 创建标题行(第一行)
Row titleRow = sheet.createRow(0);
// 设置第一行的行高
titleRow.setHeight(DEFAULT_COLUMNS_HEIGHT);
// 设置序号
sheet.setColumnWidth(0, DEFAULT_COLUMNS_WEIGHT);
Cell cell = titleRow.createCell(0);
setTitle(baseInfList, sheet, titleStyle, titleRow, cell);
/*
* 写入数据
*
* 写入数据按照先行 后列的的方式进行
*
*/
CellStyle dataStyle = dataStyle(workbook);
Row dataRow;
for (int i = 0; i < list.size(); i++) {
// 创建行
dataRow = sheet.createRow(i + 1);
// 创建列 此处为序号列
cell = dataRow.createCell(0);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(i + 1);
cell.setCellStyle(titleStyle);
// 序号列创建完毕 开始创建数据列
for (int j = 0; j < baseInfList.size(); j++) {
// 创建数据列
cell = dataRow.createCell(j + 1);
BaseInf baseInf = baseInfList.get(j);
// 设值
Method method;
Object value;
if (innerMethod != null) {
method = list.get(i).getClass().getMethod(innerMethod);
Object obj = method.invoke(list.get(i));
method = obj.getClass().getMethod(baseInf.getColumMethod());
value = method.invoke(obj);
} else {
method = list.get(i).getClass().getMethod(baseInf.getColumMethod());
value = method.invoke(list.get(i));
}
String returnType = method.getReturnType().getName().toLowerCase();
//数据处理类 处理数据库原始生成数据
Class<?> valueClazz = baseInf.getClazz();
Method valueMethod = baseInf.getMethod();
if (valueClazz != null && valueMethod != null) {
value = valueMethod.invoke(valueClazz, value);
}
cell.setCellStyle(dataStyle);
// 转义列表
Map<String, String> transMap = baseInf.getMap();
// 判断是否需要转义
if (transMap == null) {
if (returnType.contains("string")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value == null ? "" : value.toString());
} else if (returnType.contains("integer") || returnType.contains("int")
|| returnType.contains("bigdecimal") || returnType.contains("double")
|| returnType.contains("long") || returnType.contains("float")) {
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
if (value != null) {
cell.setCellValue(new Double(value.toString()));
} else {
cell.setCellValue(0.0d);
}
} else if (returnType.contains("date")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value == null ? null : sdf.format((Date) value));
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value == null ? "" : value.toString());
}
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String cellValue = value == null ? "" : transMap.get(tse(value.toString()));
cell.setCellValue(cellValue == null ? tse(value.toString()) : cellValue);
}
}
}
// 创建统计行
if (openCount) {
openCount(baseInfList, sheet, titleStyle, dataStyle, list.size());
}
return workbook;
}
public static Workbook createWorkbookForMap(int version, String sheetNm, List<BaseInf> baseInfList, List<Map<String,Object>> list,Boolean openCount) throws SecurityException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException {
SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_PATTERN);
Workbook workbook;
if (version == 2007) {
workbook = new XSSFWorkbook();
} else {
workbook = new HSSFWorkbook();
}
Sheet sheet = workbook.createSheet(isEmpty(sheetNm) ? "sheet1" : sheetNm);
// 写入标题
CellStyle titleStyle = titleStyle(workbook);
// 创建标题行(第一行)
Row titleRow = sheet.createRow(0);
// 设置第一行的行高
titleRow.setHeight(DEFAULT_COLUMNS_HEIGHT);
// 设置序号
sheet.setColumnWidth(0, DEFAULT_COLUMNS_WEIGHT);
Cell cell = titleRow.createCell(0);
setTitle(baseInfList, sheet, titleStyle, titleRow, cell);
/*
* 写入数据
* 写入数据按照先行 后列的的方式进行
*/
CellStyle dataStyle = dataStyle(workbook);
Row dataRow;
for (int i = 0; i < list.size(); i++) {
// 创建行
dataRow = sheet.createRow(i + 1);
// 创建列 此处为序号列
cell = dataRow.createCell(0);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(i + 1);
cell.setCellStyle(titleStyle);
// 序号列创建完毕 开始创建数据列
for (int j = 0; j < baseInfList.size(); j++) {
// 创建数据列
cell = dataRow.createCell(j + 1);
BaseInf baseInf = baseInfList.get(j);
// 设值
Object value = list.get(i).get(baseInf.getColumMethod());
//数据处理类 处理数据库原始生成数据
Class<?> valueClazz = baseInf.getClazz();
Method valueMethod = baseInf.getMethod();
if (valueClazz != null && valueMethod != null) {
value = valueMethod.invoke(valueClazz, value);
}
cell.setCellStyle(dataStyle);
// 转义列表
Map<String, String> transMap = baseInf.getMap();
// 判断是否需要转义
if (transMap == null) {
if(value instanceof String){
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value.toString());
}
if(value instanceof Integer || value instanceof BigDecimal || value instanceof Long){
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(new Double(value.toString()));
}
if(value instanceof Date){
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(sdf.format((Date) value));
}else {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(value == null ? "" : value.toString());
}
} else {
cell.setCellType(Cell.CELL_TYPE_STRING);
String cellValue = value == null ? "" : transMap.get(tse(value.toString()));
cell.setCellValue(cellValue == null ? tse(value.toString()) : cellValue);
}
}
}
// 创建统计行
if (openCount) {
openCount(baseInfList, sheet, titleStyle, dataStyle, list.size());
}
return workbook;
}
/**
* 设置标题
*/
private static void setTitle(List<BaseInf> baseInfList, Sheet sheet, CellStyle titleStyle, Row titleRow, Cell cell) {
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("序号");
cell.setCellStyle(titleStyle);
// 其他标题
for (int i = 0; i < baseInfList.size(); i++) {
String titleName = baseInfList.get(i).getTitleName();
// 设置单元格的宽
sheet.setColumnWidth(i + 1, titleName.length() * DEFAULT_COLUMNS_WEIGHT);
cell = titleRow.createCell(i + 1);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(titleName);
cell.setCellStyle(titleStyle);
}
}
private static void openCount(List<BaseInf> baseInfList, Sheet sheet, CellStyle titleStyle, CellStyle dataStyle, int size) {
Row dataRow;
Cell cell;
dataRow = sheet.createRow(size + 1);
// 创建列 此处为序号列
cell = dataRow.createCell(0);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue("统计");
cell.setCellStyle(titleStyle);
for (int i = 0; i < baseInfList.size(); i++) {
BaseInf baseInf = baseInfList.get(i);
cell = dataRow.createCell(i + 1);
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellStyle(dataStyle);
if (baseInf.getCount() != null) {
cell.setCellValue(baseInf.getCount());
} else {
cell.setCellValue("");
}
}
}
/**
* 删除字符串内的回车 空格和两端空白
*/
private static String tse(String str) {
return str == null ? "" : str.replace(" ", "").replace("/r", "").replace("/n", "").trim();
}
// 判断非空
private static boolean isEmpty(String str) {
return str == null || "".equals(str.trim());
}
/**
* 设置标题样式
* @param workbook 工作表
* @return 标题样式
*/
private static CellStyle titleStyle(Workbook workbook) {
CellStyle titleStyle = workbook.createCellStyle();
titleStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
titleStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
// 居中
titleStyle.setAlignment(CellStyle.ALIGN_CENTER_SELECTION);
titleStyle.setBorderLeft((short) 1);
titleStyle.setBorderRight((short) 1);
titleStyle.setBorderBottom((short) 1);
titleStyle.setBorderTop((short) 1);
Font font = workbook.createFont();
font.setFontHeightInPoints((short) 12);// 设置字体大小
titleStyle.setFont(font);// 选择需要用到的字体格式
return titleStyle;
}
/**
* 数据样式
*
* @param workbook 工作表
* @return 数据样式
*/
private static CellStyle dataStyle(Workbook workbook) {
CellStyle dataStyle = workbook.createCellStyle();
dataStyle.setBorderBottom((short) 1);
dataStyle.setBorderLeft((short) 1);
dataStyle.setBorderRight((short) 1);
dataStyle.setBorderTop((short) 1);
dataStyle.setBottomBorderColor(HSSFColor.BLACK.index);
return dataStyle;
}
}
excel文件下载工具分享相关推荐
- Python 自动化办公之 Excel 对比工具
作者 | 周萝卜 来源丨萝卜大杂烩 今天我们继续分享真实的自动化办公案例,希望各位 Python 爱好者能够从中得到些许启发,在自己的工作生活中更多的应用 Python,使得工作事半功倍! 需求 由于 ...
- Python自动化办公之Excel对比工具
今天我们继续分享真实的自动化办公案例,希望各位 Python 爱好者能够从中得到些许启发,在自己的工作生活中更多的应用 Python,使得工作事半功倍! 需求 由于工作当中经常需要对比前后两个 Exc ...
- java读写excel文件poi_Java利用POI读写Excel文件工具类
本文实例为大家分享了Java读写Excel文件工具类的具体代码,供大家参考,具体内容如下 package com.test.app.utils; import java.io.File; import ...
- excel拆分工具怎么拆分表格?
今天小编跟大家分享一下excel拆分工具怎么拆分表格? 1.首先我们打开excel文件,接着点击如下图选项 2.接着鼠标单击[汇总拆分] 3.选择[拆分工作表] 4.然后我们要处理的表格标题行数为2, ...
- excel怎么启用宏_轻便免费的Excel合并工具,支持wps和office全系统
Excel合并工具绿色程序版是一款由吾爱网友ermituofo分享制作的Excel合并软件,软件支持wps和office全系统,很多用户发表格给其他用户之后自己要使用合并处理就很麻烦,有了这个工具,就 ...
- matlab多元回归模型分析,matlab多元回归工具箱 Excel数据分析工具进行多元回归分析.doc...
matlab多元回归工具箱 Excel数据分析工具进行多元回归分析.doc matlab多元回归工具箱 Excel数据分析工具进行多元回归分析 导读:就爱阅读网友为您分享以下"Excel数据 ...
- 简洁、快速、节约内存的Excel处理工具EasyExcel
欢迎光临我的博客查看最新文章: https://river106.cn 1.简介 EasyExcel是一个基于Java的.快速.简洁.解决大文件内存溢出的Excel处理工具. 他能让你在不用考虑 ...
- 【工具分享篇二】PDF公式提取教程(一):Mathpix/Typora及Pandoc扩展安装教程
前言 这期我们来分享几个应用的下载与安装教程,以保障下一篇<PDF公式提取教程(二)>的软件条件 [工具分享篇]PDF公式提取教程(二)_Liam77的博客-CSDN博客[工具分享篇]PD ...
- Excel导出工具类
前言 相信不少同学在开发中都会遇到导出excel这种需求,今天将Excel的导出工具和大家进行一个分享,如有错误还请大佬们批评指正.该工具类可以实现自定义列宽,自定义表头样式,实现了多sheet页合并 ...
最新文章
- Maven中的profile和spring boot中的profile进行结合
- 小学五年级就已经开始编程啦吗???
- Spring.NET学习笔记10——方法的注入(基础篇) Level 200
- 41 | 案例篇:如何优化 NAT 性能?(上)
- python整形不可迭代_Python – TypeError:’int’对象不可迭代
- GDI与OpenGL与DirectX之间的区别
- reboot重启失败的解决方法
- 在Ubuntu下安装jdk解压出现问题:./jdk-6u30-linux-i586.bin: 113: ./install.sfx.3631: not found
- 宁浩:扛过了,痛便是痛快!
- C++常见谬误总结(1)
- python数据结构6 -二叉树
- Go语言之高级篇beego框架之模型(Models)
- 概率扩散模型 Probabilistic Diffusion Model
- (Python数字图像处理)自适应中值滤波算法
- 斐波那契数列c语言while,C语言数据结构递归之斐波那契数列
- cpci检索太慢_了解CPCI检索,对自己的好处
- 上海电信账单余额查询接口
- 破解Excel保护密码
- python变量的声明和赋值
- 基于制导武器的分布式半实物仿真系统ETest研究