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

相关文章

揭秘未来艺术:AI绘画工具全面介绍

📑前言 随着科技的飞速发展,人工智能(AI)已经逐渐渗透到我们生活的方方面面。在艺术创作领域,AI技术同样展现出了其独特的魅力。今天,我们就来一起探索这个神秘而引人入胜的领域,深入了解AI绘画工具的奥秘及其为艺术创作带来的革命性变革。 一、AI绘画工具的崛起 1.1 颠覆传统绘画模式 在过去,绘画是艺术家们通过手中的画笔,蘸取颜料,在画布上自由挥洒的创造性过程。然而,随着AI绘画工

墨刀原型工具-小白入门篇

墨刀原型工具-小白入门篇 简介 随着互联网的发展和用户体验的重要性越来越受到重视,原型设计逐渐成为了产品设计中的重要环节。墨刀作为一款原型设计工具,以其简洁、易用的特点,受到了很多设计师的喜爱。本文将介绍墨刀原型工具的基本使用方法,以帮助小白快速上手。 第一章:认识墨刀原型工具 1.1 什么是墨刀原型工具 墨刀是一款基于Web的原型设计工具,可以帮助设计师快速创建交互原型,并且可以与团队

大学湖北中医药大学法医学试题及答案,分享几个实用搜题和学习工具 #微信#学习方法#职场发展

今天分享拥有拍照搜题、文字搜题、语音搜题、多重搜题等搜题模式,可以快速查找问题解析,加深对题目答案的理解。 1.快练题 这是一个网站 找题的网站海量题库,在线搜题,快速刷题~为您提供百万优质题库,直接搜索题库名称,支持多种刷题模式:顺序练习、语音听题、本地搜题、顺序阅读、模拟考试、组卷考试、赶快下载吧! 2.彩虹搜题 这是个老公众号了 支持手写输入,截图搜题,详细步骤,解题必备

Mac excel 同时冻结首行和首列

1. 选择B2窗格 2. 选择视图 3. 选择冻结窗格 最后首行和首列的分割线加粗了就表示成功了

Windows/macOS/Linux 安装 Redis 和 Redis Desktop Manager 可视化工具

本文所有安装都在macOS High Sierra 10.13.4进行,Windows安装相对容易些,Linux安装与macOS类似,文中会做区分讲解 1. Redis安装 1.下载Redis https://redis.io/download 把下载的源码更名为redis-4.0.9-source,我喜欢跟maven、Tomcat放在一起,就放到/Users/zhan/Documents

OpenCompass:大模型测评工具

大模型相关目录 大模型,包括部署微调prompt/Agent应用开发、知识库增强、数据库增强、知识图谱增强、自然语言处理、多模态等大模型应用开发内容 从0起步,扬帆起航。 大模型应用向开发路径:AI代理工作流大模型应用开发实用开源项目汇总大模型问答项目问答性能评估方法大模型数据侧总结大模型token等基本概念及参数和内存的关系大模型应用开发-华为大模型生态规划从零开始的LLaMA-Factor

简鹿文件批量重命名:一款文件批量改名高手都在用的工具

作为 IT 行业的搬砖民工,互联网的数据量爆炸性增长,文件管理成为了一项日益重要的任务。"简鹿文件批量重命名"应运而生,旨在为用户提供一个高效、灵活的解决方案,以应对繁琐的文件命名、排序、创建及属性修改等挑战。 这款软件凭借其一键式操作、强大的自定义规则导入、以及全面的批量处理能力,极大地简化了文件管理流程,尤其适合处理大量文件的个人用户及企业环境,是提高工作效率、保持文件系统整洁的得力助手

LeetCode--171 Excel表列序号

题目 给定一个Excel表格中的列名称,返回其相应的列序号。例如,A -> 1B -> 2C -> 3...Z -> 26AA -> 27AB -> 28 ... 示例 示例 1:输入: "A"输出: 1示例 2:输入: "AB"输出: 28示例 3:输入: "ZY"输出: 701 class Solution {public:int titleToNumber(strin

如何用外呼工具和CRM管理系统形成销售闭环

使用外呼工具和CRM管理系统形成销售闭环是一个系统性的过程,它涉及客户数据的整合、个性化的营销活动、销售与市场活动的协作、顾客行为的追踪与理解以及营销成效的评估与优化等多个环节。 以下是如何将外呼工具和CRM管理系统有效结合以形成销售闭环的步骤: 1. 客户数据的整合与分析    - 外呼工具在与客户进行初步沟通时,会收集到客户的基本信息和初步需求。    - 这些信息随后被输入到CRM管

浅谈 MySQL for excel

欢迎关注微信公众号“Python生态智联”  MySQL for excel是一个大小只有几兆的MySQL附件,它能让我们在Microsoft excel中处理MySQL数据。小编用了两天时间浏览了MySQL for excel的使用指南并按demo演示了一遍(手册地址https://dev.mysql.com/doc/mysql-for-excel/en/),现从功能和局限两方面对MySQL