Excel导出工具类.

2024-05-16 01:38
文章标签 工具 excel 导出

本文主要是介绍Excel导出工具类.,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 Excel导出工具类.--POI

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;import org.apache.commons.lang3.ArrayUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
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.RichTextString;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import com.anhry.app.util.bean.SystemBean;
import com.anhry.app.util.excel.annoation.Excel;/*** Excel导出工具类.*/
public class ExportExcel<T> {public static final Logger LOG = LoggerFactory.getLogger(ExportExcel.class);/*** * @param title     Sheet名字* @param pojoClass Excel对象Class* @param dataSet   Excel对象数据List* @param out       输出流*/public void exportExcel(String title, Class<T> pojoClass,Collection<T> dataSet, OutputStream out) {// 使用userModel模式实现的,当excel文档出现10万级别的大数据文件可能导致OOM内存溢出exportExcelInUserModel(title, pojoClass, dataSet, out);// 使用eventModel实现,可以一边读一边处理,效率较高,但是实现复杂,暂时未实现}private void exportExcelInUserModel(String title, Class<T> pojoClass,Collection<T> dataSet, OutputStream out) {try {// 首先检查数据看是否是正确的if (dataSet == null || dataSet.size() == 0) {throw new Exception("导出数据为空!");}if (title == null || out == null || pojoClass == null) {throw new Exception("传入参数不能为空!");}// 声明一个工作薄Workbook workbook = new HSSFWorkbook();// 生成一个表格Sheet sheet = workbook.createSheet(title);// 标题List<String> exportFieldTitle = new ArrayList<String>();List<Integer> exportFieldWidth = new ArrayList<Integer>();// 拿到所有列名,以及导出的字段的get方法List<Method> methodObj = new ArrayList<Method>();Map<String, Method> convertMethod = new HashMap<String, Method>();// 得到所有字段Field fileds[] = pojoClass.getDeclaredFields();// 遍历整个filedfor (int i = 0; i < fileds.length; i++) {Field field = fileds[i];Excel excel = field.getAnnotation(Excel.class);// 如果设置了annottionif (excel != null) {// 添加到标题exportFieldTitle.add(excel.exportName());// 添加标题的列宽exportFieldWidth.add(excel.exportFieldWidth());// 添加到需要导出的字段的方法String fieldname = field.getName();// System.out.println(i+"列宽"+excel.exportName()+" "+excel.exportFieldWidth());StringBuffer getMethodName = new StringBuffer("get");getMethodName.append(fieldname.substring(01).toUpperCase());getMethodName.append(fieldname.substring(1));Method getMethod = pojoClass.getMethod(getMethodName.toString(), new Class[] {});methodObj.add(getMethod);if (excel.exportConvert() == true) {StringBuffer getConvertMethodName = new StringBuffer("get");getConvertMethodName.append(fieldname.substring(01).toUpperCase());getConvertMethodName.append(fieldname.substring(1));getConvertMethodName.append("Convert");Method getConvertMethod = pojoClass.getMethod(getConvertMethodName.toString(),new Class[] {});convertMethod.put(getMethodName.toString(),getConvertMethod);}}}int index = 0;// 产生表格标题行Row row = sheet.createRow(index);for (int i = 0, exportFieldTitleSize = exportFieldTitle.size(); i < exportFieldTitleSize; i++) {Cell cell = row.createCell(i);// cell.setCellStyle(style);RichTextString text = new HSSFRichTextString(exportFieldTitle.get(i));cell.setCellValue(text);}// 设置每行的列宽for (int i = 0; i < exportFieldWidth.size(); i++) {// 256=65280/255sheet.setColumnWidth(i, 256 * exportFieldWidth.get(i));}Iterator its = dataSet.iterator();// 循环插入剩下的集合while (its.hasNext()) {// 从第二行开始写,第一行是标题index++;row = sheet.createRow(index);Object t = its.next();for (int k = 0, methodObjSize = methodObj.size(); k < methodObjSize; k++) {Cell cell = row.createCell(k);Method getMethod = methodObj.get(k);Object value = null;if (convertMethod.containsKey(getMethod.getName())) {Method cm = convertMethod.get(getMethod.getName());value = cm.invoke(t, new Object[] {});} else {value = getMethod.invoke(t, new Object[] {});}cell.setCellValue(value == null ? "" : value.toString());}}workbook.write(out);} catch (Exception e) {e.printStackTrace();}}/*** * @param title     Sheet名字* @param pojoClass Excel对象Class* @param dataSet   Excel对象数据List* @param out       输出流*/public HSSFWorkbook  exportExcel(String title, Class<T> pojoClass,Collection<T> dataSet) {// 使用userModel模式实现的,当excel文档出现10万级别的大数据文件可能导致OOM内存溢出return exportExcelInUserModel2File(title, pojoClass, dataSet, null);}/*** * @param title     Sheet名字* @param pojoClass Excel对象Class* @param dataSet   Excel对象数据List* @param exportFields   Excel对象选择要导出的字段 * @param out       输出流*/public HSSFWorkbook  exportExcel(String title, Class<T> pojoClass,Collection<T> dataSet,List<String> exportFields) {// 使用userModel模式实现的,当excel文档出现10万级别的大数据文件可能导致OOM内存溢出return exportExcelInUserModel2File(title, pojoClass, dataSet, exportFields);}HSSFWorkbook exportExcelInUserModel2File(String title, Class<T> pojoClass,Collection<T> dataSet)  {return exportExcelInUserModel2File(title, pojoClass, dataSet, null);}private HSSFWorkbook exportExcelInUserModel2File(String title, Class<T> pojoClass,Collection<T> dataSet, List<String> exportFields) {// 声明一个工作薄HSSFWorkbook  workbook = null;try {// 声明一个工作薄workbook = new HSSFWorkbook();// 生成一个表格Sheet sheet = workbook.createSheet(title);// 标题List<String> exportFieldTitle = new ArrayList<String>();List<Integer> exportFieldWidth = new ArrayList<Integer>();// 拿到所有列名,以及导出的字段的get方法List<Method> methodObj = new ArrayList<Method>();Map<String, Method> convertMethod = new HashMap<String, Method>();Class superClazz = null;Field fileds[] = new Field[0];boolean flag = true;while (flag) {if(superClazz != null){superClazz = superClazz.getSuperclass();}else{superClazz = pojoClass.getSuperclass();}if(superClazz.isInstance(Object.class)){flag = false;}else{Field[] sf = superClazz.getDeclaredFields();if(sf != null && sf.length >0){for(int m = 0;m<sf.length;m++){fileds = ArrayUtils.addAll(fileds, sf[m]);}}}}// 得到所有字段Field cfileds[] = pojoClass.getDeclaredFields();if(cfileds != null && cfileds.length >0){for(int n = 0;n<cfileds.length;n++){fileds = ArrayUtils.addAll(fileds, cfileds[n]);}}// 遍历整个filedint exportFieldCount = 0// 要导出字段的数量if(exportFields != null && exportFields.size() > 0) {exportFieldCount = exportFields.size() ; }for (int i = 0; i < fileds.length; i++) {Field field = fileds[i];Excel excel = field.getAnnotation(Excel.class);// 如果设置了annottionif (excel != null) {if(exportFieldCount > 0) {for(String eField: exportFields) {if(eField.equals(excel.exportName())) {addExportField(exportFieldTitle, exportFieldWidth, excel, field, methodObj, pojoClass, convertMethod);exportFieldCount -=1;LOG.debug("exportFieldCount  --- > " + exportFieldCount);break;}}if(exportFieldCount <= 0) {LOG.debug("Break Field Loop!   ------------ !@!");break;}} else {addExportField(exportFieldTitle, exportFieldWidth, excel, field, methodObj, pojoClass, convertMethod);}}}int index = 0;// 产生表格标题行Row row = sheet.createRow(index);row.setHeight((short)450);CellStyle titleStyle = getTitleStyle(workbook);for (int i = 0, exportFieldTitleSize = exportFieldTitle.size(); i < exportFieldTitleSize; i++) {Cell cell = row.createCell(i);// cell.setCellStyle(style);RichTextString text = new HSSFRichTextString(exportFieldTitle.get(i));cell.setCellValue(text);cell.setCellStyle(titleStyle);}// 设置每行的列宽for (int i = 0; i < exportFieldWidth.size(); i++) {// 256=65280/255sheet.setColumnWidth(i, 256 * exportFieldWidth.get(i));}Iterator its = dataSet.iterator();// 循环插入剩下的集合HSSFCellStyle oneStyle = getOneStyle(workbook);HSSFCellStyle twoStyle = getTwoStyle(workbook);while (its.hasNext()) {// 从第二行开始写,第一行是标题index++;row = sheet.createRow(index);row.setHeight((short)350);Object t = its.next();for (int k = 0, methodObjSize = methodObj.size(); k < methodObjSize; k++) {Cell cell = row.createCell(k);Method getMethod = methodObj.get(k);Object value = null;if (convertMethod.containsKey(getMethod.getName())) {Method cm = convertMethod.get(getMethod.getName());value = cm.invoke(t, new Object[] {});} else {value = getMethod.invoke(t, new Object[] {});}cell.setCellValue(value==null?"":value.toString());if(index%2==0)cell.setCellStyle(twoStyle);elsecell.setCellStyle(oneStyle);}}} catch (Exception e) {e.printStackTrace();}return workbook;}private void addExportField(List<String> exportFieldTitle, List<Integer> exportFieldWidth, Excel excel, Field field, List<Method> methodObj, Class<T> pojoClass, Map<String, Method> convertMethod) throws Exception{// 添加到标题exportFieldTitle.add(excel.exportName());// 添加标题的列宽exportFieldWidth.add(excel.exportFieldWidth());// 添加到需要导出的字段的方法String fieldname = field.getName();// System.out.println(i+"列宽"+excel.exportName()+" "+excel.exportFieldWidth());StringBuffer getMethodName = new StringBuffer("get");getMethodName.append(fieldname.substring(01).toUpperCase());getMethodName.append(fieldname.substring(1));Method getMethod = pojoClass.getMethod(getMethodName.toString(), new Class[] {});methodObj.add(getMethod);if (excel.exportConvert() == true) {//----------------------------------------------------------------//update-begin--Author:Quainty  Date:20130524 for:[8]excel导出时间问题// 用get/setXxxxConvert方法名的话, 由于直接使用了数据库绑定的Entity对象,注入会有冲突StringBuffer getConvertMethodName = new StringBuffer("convertGet");getConvertMethodName.append(fieldname.substring(01).toUpperCase());getConvertMethodName.append(fieldname.substring(1));//getConvertMethodName.append("Convert");//update-end--Author:Quainty  Date:20130524 for:[8]excel导出时间问题//----------------------------------------------------------------// System.out.println("convert: "+getConvertMethodName.toString());Method getConvertMethod = pojoClass.getMethod(getConvertMethodName.toString(),new Class[] {});convertMethod.put(getMethodName.toString(),getConvertMethod);}}/*** 取得一个类添加了@Excel 注解的所有属性中 该注解中的exportName* @param pojoClass* @return*/public  List<SystemBean> getExportFields(Class<T> pojoClass) {// 标题List<SystemBean> exportNames = new ArrayList<SystemBean>();Class superClazz = null;Field fileds[] = new Field[0];boolean flag = true;while (flag) {if(superClazz != null){superClazz = superClazz.getSuperclass();}else{superClazz = pojoClass.getSuperclass();}if(superClazz.isInstance(Object.class)){flag = false;}else{Field[] sf = superClazz.getDeclaredFields();if(sf != null && sf.length >0){for(int m = 0;m<sf.length;m++){fileds = ArrayUtils.addAll(fileds, sf[m]);System.out.println(sf[m].getName());}}}}// 得到所有字段Field cfileds[] = pojoClass.getDeclaredFields();if(cfileds != null && cfileds.length >0){for(int n = 0;n<cfileds.length;n++){fileds = ArrayUtils.addAll(fileds, cfileds[n]);}}// 遍历整个filedfor (int i = 0; i < fileds.length; i++) {Field field = fileds[i];Excel excel = field.getAnnotation(Excel.class);// 如果设置了annottionif (excel != null) {SystemBean sb = new SystemBean();sb.setId(excel.exportName());sb.setName(excel.exportName());// 添加到标题exportNames.add(sb);}}return exportNames;}/*** 导出excel的样式* @param workbook* @return*/public static HSSFCellStyle getTitleStyle(HSSFWorkbook workbook){// 产生Excel表头HSSFCellStyle titleStyle = workbook.createCellStyle();titleStyle.setBorderBottom(HSSFCellStyle.BORDER_DOUBLE);    //设置边框样式titleStyle.setBorderLeft((short)2);     //左边框titleStyle.setBorderRight((short)2);    //右边框titleStyle.setBorderTop((short)2);     //左边框titleStyle.setBorderBottom((short)2);    //右边框titleStyle.setBorderTop(HSSFCellStyle.BORDER_DOUBLE);    //顶边框titleStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index);    //填充的背景颜色titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    //填充图案return titleStyle;}public static HSSFCellStyle getTwoStyle(HSSFWorkbook workbook){// 产生Excel表头// 产生Excel表头HSSFCellStyle style = workbook.createCellStyle(); style.setBorderLeft((short)1);     //左边框style.setBorderRight((short)1);    //右边框style.setBorderBottom((short)1);style.setBorderTop((short)1);style.setFillForegroundColor(HSSFColor.LIGHT_TURQUOISE.index);    //填充的背景颜色style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);    //填充图案return style;}public static HSSFCellStyle getOneStyle(HSSFWorkbook workbook){// 产生Excel表头// 产生Excel表头HSSFCellStyle style = workbook.createCellStyle(); style.setBorderLeft((short)1);     //左边框style.setBorderRight((short)1);    //右边框style.setBorderBottom((short)1);style.setBorderTop((short)1); return style;}}

这篇关于Excel导出工具类.的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/993513

相关文章

使用Python删除Excel中的行列和单元格示例详解

《使用Python删除Excel中的行列和单元格示例详解》在处理Excel数据时,删除不需要的行、列或单元格是一项常见且必要的操作,本文将使用Python脚本实现对Excel表格的高效自动化处理,感兴... 目录开发环境准备使用 python 删除 Excphpel 表格中的行删除特定行删除空白行删除含指定

SpringBoot+EasyExcel实现自定义复杂样式导入导出

《SpringBoot+EasyExcel实现自定义复杂样式导入导出》这篇文章主要为大家详细介绍了SpringBoot如何结果EasyExcel实现自定义复杂样式导入导出功能,文中的示例代码讲解详细,... 目录安装处理自定义导出复杂场景1、列不固定,动态列2、动态下拉3、自定义锁定行/列,添加密码4、合并

Python办公自动化实战之打造智能邮件发送工具

《Python办公自动化实战之打造智能邮件发送工具》在数字化办公场景中,邮件自动化是提升工作效率的关键技能,本文将演示如何使用Python的smtplib和email库构建一个支持图文混排,多附件,多... 目录前言一、基础配置:搭建邮件发送框架1.1 邮箱服务准备1.2 核心库导入1.3 基础发送函数二、

基于Python实现一个图片拆分工具

《基于Python实现一个图片拆分工具》这篇文章主要为大家详细介绍了如何基于Python实现一个图片拆分工具,可以根据需要的行数和列数进行拆分,感兴趣的小伙伴可以跟随小编一起学习一下... 简单介绍先自己选择输入的图片,默认是输出到项目文件夹中,可以自己选择其他的文件夹,选择需要拆分的行数和列数,可以通过

Python使用pip工具实现包自动更新的多种方法

《Python使用pip工具实现包自动更新的多种方法》本文深入探讨了使用Python的pip工具实现包自动更新的各种方法和技术,我们将从基础概念开始,逐步介绍手动更新方法、自动化脚本编写、结合CI/C... 目录1. 背景介绍1.1 目的和范围1.2 预期读者1.3 文档结构概述1.4 术语表1.4.1 核

Python使用OpenCV实现获取视频时长的小工具

《Python使用OpenCV实现获取视频时长的小工具》在处理视频数据时,获取视频的时长是一项常见且基础的需求,本文将详细介绍如何使用Python和OpenCV获取视频时长,并对每一行代码进行深入解析... 目录一、代码实现二、代码解析1. 导入 OpenCV 库2. 定义获取视频时长的函数3. 打开视频文

Linux中压缩、网络传输与系统监控工具的使用完整指南

《Linux中压缩、网络传输与系统监控工具的使用完整指南》在Linux系统管理中,压缩与传输工具是数据备份和远程协作的桥梁,而系统监控工具则是保障服务器稳定运行的眼睛,下面小编就来和大家详细介绍一下它... 目录引言一、压缩与解压:数据存储与传输的优化核心1. zip/unzip:通用压缩格式的便捷操作2.

Java easyExcel实现导入多sheet的Excel

《JavaeasyExcel实现导入多sheet的Excel》这篇文章主要为大家详细介绍了如何使用JavaeasyExcel实现导入多sheet的Excel,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录1.官网2.Excel样式3.代码1.官网easyExcel官网2.Excel样式3.代码

sqlite3 命令行工具使用指南

《sqlite3命令行工具使用指南》本文系统介绍sqlite3CLI的启动、数据库操作、元数据查询、数据导入导出及输出格式化命令,涵盖文件管理、备份恢复、性能统计等实用功能,并说明命令分类、SQL语... 目录一、启动与退出二、数据库与文件操作三、元数据查询四、数据操作与导入导出五、查询输出格式化六、实用功

Java Web实现类似Excel表格锁定功能实战教程

《JavaWeb实现类似Excel表格锁定功能实战教程》本文将详细介绍通过创建特定div元素并利用CSS布局和JavaScript事件监听来实现类似Excel的锁定行和列效果的方法,感兴趣的朋友跟随... 目录1. 模拟Excel表格锁定功能2. 创建3个div元素实现表格锁定2.1 div元素布局设计2.