新人使用比较low的Excel,后期会做优化提升。

一、首先放入我们所需要的依赖;

 <!-- 解析excel --><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><!-- 阿里巴巴EasyExcel--><groupId>com.alibaba</groupId><artifactId>easyexcel</artifactId><version>1.1.2-beta4</version></dependency>

二、放入我们的相关工具类;
1). 获取HttpServlet子对象的类: HttpServletUtil;


import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;/**
* 获取HttpServlet子对象
* @author todo
* @date 2020/10/15
*/
public class HttpServletUtil {/*** 获取ServletRequestAttributes对象*/public static ServletRequestAttributes getServletRequest(){return (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();}/*** 获取HttpServletRequest对象*/public static HttpServletRequest getRequest(){return getServletRequest().getRequest();}/*** 获取HttpServletResponse对象*/public static HttpServletResponse getResponse(){return getServletRequest().getResponse();}/*** 获取请求参数*/public static String getParameter(String param){return getRequest().getParameter(param);}/*** 获取请求参数,带默认值*/public static String getParameter(String param, String defaultValue){String parameter = getRequest().getParameter(param);return StringUtils.isEmpty(parameter) ? defaultValue : parameter;}/*** 获取请求参数转换为int类型*/public static Integer getParameterInt(String param){return Integer.valueOf(getRequest().getParameter(param));}/*** 获取请求参数转换为int类型,带默认值*/public static Integer getParameterInt(String param, Integer defaultValue){return Integer.valueOf(getParameter(param, String.valueOf(defaultValue)));}public static String getParameterString(String param, String defaultValue){return String.valueOf(getParameter(param, defaultValue));}
}

2)导入工具类:ExcelUtil

package com.todosoft.hzct.modules.cockpit.util;import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.BaseRowModel;
import com.alibaba.excel.metadata.Sheet;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.*;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;/*** @description:* @author: chenmingjian* @date: 19-3-18 16:16*/
@Slf4j
public class ExcelUtil {private static Sheet initSheet;static {initSheet = new Sheet(1, 0);initSheet.setSheetName("sheet");//设置自适应宽度initSheet.setAutoWidth(Boolean.TRUE);}/*** 读取少于1000行数据** @param filePath 文件绝对路径* @return*/public static List<Object> readLessThan1000Row(String filePath) {return readLessThan1000RowBySheet(filePath, null);}/*** 读小于1000行数据, 带样式* filePath 文件绝对路径* initSheet :* sheetNo: sheet页码,默认为1* headLineMun: 从第几行开始读取数据,默认为0, 表示从第一行开始读取* clazz: 返回数据List<Object> 中Object的类名*/public static List<Object> readLessThan1000RowBySheet(String filePath, Sheet sheet) {if (!StringUtils.hasText(filePath)) {return null;}sheet = sheet != null ? sheet : initSheet;InputStream fileStream = null;try {fileStream = new FileInputStream(filePath);return EasyExcelFactory.read(fileStream, sheet);} catch (FileNotFoundException e) {log.info("找不到文件或文件路径错误, 文件:{}", filePath);} finally {try {if (fileStream != null) {fileStream.close();}} catch (IOException e) {log.info("excel文件读取失败, 失败原因:{}", e);}}return null;}/*** 读大于1000行数据** @param filePath 文件觉得路径* @return*/public static List<Object> readMoreThan1000Row(String filePath) {return readMoreThan1000RowBySheet(filePath, null);}/*** 读大于1000行数据, 带样式** @param filePath 文件觉得路径* @return*/public static List<Object> readMoreThan1000RowBySheet(String filePath, Sheet sheet) {if (!StringUtils.hasText(filePath)) {return null;}sheet = sheet != null ? sheet : initSheet;InputStream fileStream = null;try {fileStream = new FileInputStream(filePath);ExcelListener excelListener = new ExcelListener();EasyExcelFactory.readBySax(fileStream, sheet, excelListener);return excelListener.getDatas();} catch (FileNotFoundException e) {log.error("找不到文件或文件路径错误, 文件:{}", filePath);} finally {try {if (fileStream != null) {fileStream.close();}} catch (IOException e) {log.error("excel文件读取失败, 失败原因:{}", e);}}return null;}/*** 生成excle** @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx* @param data     数据源* @param head     表头*/public static void writeBySimple(String filePath, List<List<Object>> data, List<String> head) {writeSimpleBySheet(filePath, data, head, null);}/*** 生成excle** @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx* @param data     数据源* @param sheet    excle页面样式* @param head     表头*/public static void writeSimpleBySheet(String filePath, List<List<Object>> data, List<String> head, Sheet sheet) {sheet = (sheet != null) ? sheet : initSheet;if (head != null) {List<List<String>> list = new ArrayList<>();head.forEach(h -> list.add(Collections.singletonList(h)));sheet.setHead(list);}OutputStream outputStream = null;ExcelWriter writer = null;try {outputStream = new FileOutputStream(filePath);writer = EasyExcelFactory.getWriter(outputStream);writer.write1(data, sheet);} catch (FileNotFoundException e) {log.error("找不到文件或文件路径错误, 文件:{}", filePath);} finally {try {if (writer != null) {writer.finish();}if (outputStream != null) {outputStream.close();}} catch (IOException e) {log.error("excel文件导出失败, 失败原因:{}", e);}}}/*** 生成excle** @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx* @param data     数据源*/public static void writeWithTemplate(String filePath, List<? extends BaseRowModel> data) {writeWithTemplateAndSheet(filePath, data, null);}/*** 生成excle** @param filePath 绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx* @param data     数据源* @param sheet    excle页面样式*/public static void writeWithTemplateAndSheet(String filePath, List<? extends BaseRowModel> data, Sheet sheet) {if (CollectionUtils.isEmpty(data)) {return;}sheet = (sheet != null) ? sheet : initSheet;sheet.setClazz(data.get(0).getClass());OutputStream outputStream = null;ExcelWriter writer = null;try {outputStream = new FileOutputStream(filePath);writer = EasyExcelFactory.getWriter(outputStream);writer.write(data, sheet);XSSFWorkbook workbook = null;download(workbook, filePath);} catch (FileNotFoundException e) {log.error("找不到文件或文件路径错误, 文件:{}", filePath);} finally {try {if (writer != null) {writer.finish();}if (outputStream != null) {outputStream.close();}} catch (IOException e) {log.error("excel文件导出失败, 失败原因:{}", e);}}}/*** 下载操作*/private static void download(XSSFWorkbook workbook, String fileName) {try {fileName = URLEncoder.encode(fileName + ".xlsx", "utf-8");} catch (UnsupportedEncodingException e) {e.printStackTrace();}HttpServletResponse response = HttpServletUtil.getResponse();response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);OutputStream ros = null;try {ros = response.getOutputStream();workbook.write(ros);ros.flush();} catch (IOException e) {e.printStackTrace();} finally {if (ros != null) {try {ros.close();} catch (IOException e) {e.printStackTrace();}}if (workbook != null) {try {workbook.close();} catch (IOException e) {e.printStackTrace();}}}}/*** 生成多Sheet的excle** @param filePath              绝对路径, 如:/home/chenmingjian/Downloads/aaa.xlsx* @param multipleSheelPropetys*/public static void writeWithMultipleSheel(String filePath, List<MultipleSheelPropety> multipleSheelPropetys) {if (CollectionUtils.isEmpty(multipleSheelPropetys)) {return;}OutputStream outputStream = null;ExcelWriter writer = null;try {outputStream = new FileOutputStream(filePath);writer = EasyExcelFactory.getWriter(outputStream);for (MultipleSheelPropety multipleSheelPropety : multipleSheelPropetys) {Sheet sheet = multipleSheelPropety.getSheet() != null ? multipleSheelPropety.getSheet() : initSheet;if (!CollectionUtils.isEmpty(multipleSheelPropety.getData())) {sheet.setClazz(multipleSheelPropety.getData().get(0).getClass());}writer.write(multipleSheelPropety.getData(), sheet);}} catch (FileNotFoundException e) {log.error("找不到文件或文件路径错误, 文件:{}", filePath);} finally {try {if (writer != null) {writer.finish();}if (outputStream != null) {outputStream.close();}} catch (IOException e) {log.error("excel文件导出失败, 失败原因:{}", e);}}}@Datapublic static class MultipleSheelPropety {private List<? extends BaseRowModel> data;private Sheet sheet;}/*** 解析监听器,* 每解析一行会回调invoke()方法。* 整个excel解析结束会执行doAfterAllAnalysed()方法** @author: chenmingjian* @date: 19-4-3 14:11*/@Getter@Setterpublic static class ExcelListener extends AnalysisEventListener {private List<Object> datas = new ArrayList<>();/*** 逐行解析* object : 当前行的数据*/@Overridepublic void invoke(Object object, AnalysisContext context) {//当前行// context.getCurrentRowNum()if (object != null) {datas.add(object);}}/*** 解析完所有数据后会调用该方法*/@Overridepublic void doAfterAllAnalysed(AnalysisContext context) {//解析结束销毁不用的资源}}public static void exportExcel(HttpServletResponse response,List<String> headers,List<String[]> list,String fileName) {//创建输出流OutputStream out = null;try {//导出的为Excel2007及以后的格式response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");//设置文件名为utf-8编码response.addHeader("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("utf-8"), "ISO8859-1")+".xlsx");out = response.getOutputStream();//调用生成excel的方法exportExcelMap(fileName, headers, list, out);} catch (Exception e) {//            logger.error("检修记录信息导出EXCEL方法失败:" + e.toString());} finally {try {if (out != null) {out.close();}} catch (Exception e) {//                logger.error("检修记录信息关闭流失败:" + e.toString());}}}/*** map转化Excel方法** @param title   文件名* @param headers 表头* @param list    数据list* @param out     输出流*/public static void exportExcelMap(String title, List<String>  headers,List<String[]> list, OutputStream out) {// 声明一个工作薄 xlsx格式XSSFWorkbook workbook = new XSSFWorkbook();// 生成一个表格XSSFSheet sheet = workbook.createSheet(title);// 设置表格默认列宽度为15个字节sheet.setDefaultColumnWidth(20);// 设置列宽
//        sheet.setColumnWidth((short) 1, 50);// 设置列宽
//        sheet.setColumnWidth((short) 2,50);// 生成一个样式XSSFCellStyle style = workbook.createCellStyle();XSSFCellStyle bigStyle = workbook.createCellStyle();bigStyle.setWrapText(true);XSSFRow row = sheet.createRow(0);String[] headerStr = headers.toArray(new String[headers.size()]);for (short i = 0; i < headerStr.length; i++) {XSSFCell cell = row.createCell(i);cell.setCellStyle(style);XSSFRichTextString text = new XSSFRichTextString(headerStr[i]);cell.setCellValue(text);}/*判断第一列是不是序号列*/short ii = 0;boolean numFlag = false;String firstColumn = "序号";if (firstColumn.equals(headerStr[0])) {ii = 1;numFlag = true;}//遍历集合数据,产生数据行int index = 0;int exportNum = 1;for (String[] str : list) {index++;row = sheet.createRow(index);if (numFlag) {/*序号列*/XSSFCell cellNum = row.createCell(0);cellNum.setCellValue(exportNum++);cellNum.setCellStyle(style);}for (short i = ii; i < headerStr.length; i++) {XSSFCell cell = row.createCell(i);cell.setCellStyle(style);cell.setCellValue(str[i]);}}try {workbook.write(out);} catch (Exception e) {e.printStackTrace();}}
}

注: 这就是我们所需要配置的东西(1.三个pom文件的依赖,2.两个工具类的导入), 别问细节 ,问就是不会。

三、下面开始使用工具类;

    /*** 数据下载,不需要验证**/@GetMapping("/downLoadExcel")public void exportList(HttpServletResponse response, IndexBase indexBase) throws Exception {//controller通过service调用excel工具方法;****Service.exportList(response, indexBase);}

// 实现类写法;@Overridepublic void exportList(HttpServletResponse response, IndexBase indexBase) {//list: 封装了对象的集合;List<IndexBase> list = getIndexBaseList(indexBase);// 表数据List<String[]> data = new ArrayList<>();for (int i = 0; i < list.size(); i++) {//data中封装了一个个的string类型的数组,每一个数组都是封装着一行数据;   将对象中的数据,添加到数组中去;String[] str = new String[19];str[0] = IndexBase.getownerName();str[1] = IndexBase.getname();str[2] = IndexBase.getclassName();str[3] = IndexBase.gettypes();data.add(str);}//head:List<String> head = Arrays.asList("XXX", "XXX", "XXX", "XXX");String  fileName= "表名"ExcelUtil.exportExcel(response, head, data,fileName);}

到这演示就完毕了,东西比较low 但是适合新手上手; (我说我自己),以后遇到更好的会继续更新~~鞠躬求赞哈;

比较lowB的Excel初始使用,相关推荐

  1. python3 reqeusts后写入excel

    用python通过手机号批量辨别运营商并写入excel 初始文件: 具体代码: #coding=utf-8 import requests import re import xlrd import x ...

  2. Unity中对Excel的操作(使用EPPlus)

    目录 一.导入EPPlus 1.首先在Unity中导入EPPlus和Excel 2.创建脚本,引入命名空间​​​​​​​ 二.读取Excel 1. 获取Excel信息文件 2.打开Excel文件信息, ...

  3. 小牛客户管理软件 下载

    Welcome to my blog! <script language="javascript" src="http://avss.b15.cnwg.cn/cou ...

  4. 快速恢复Word、Excel的默认初始设置

    1.word的恢复 方法1.点开始--运行,输入"winword /a"(不含引号)        回车后会启动word,所有界面和设置都恢复了初始状态,简单吧! 方法2.首先关闭 ...

  5. python二元函数求导_用Excel和python实现二元函数梯度下降的人工智能,之用,excel,一元...

    梯度下降法和牛顿法的总结与比较 机器学习的本质是建立优化模型,通过优化方法,不断迭代参数向量,找到使目标函数最优的参数向量.最终建立模型 通常用到的优化方法:梯度下降方法.牛顿法.拟牛顿法等.这些优化 ...

  6. NR:UE初始搜网流程

    UE的初始搜网流程,PSS->SSS->PBCH->RMSI.我画了一个简单的流程图如下,里面标注了每个环节的重点. UE的初始搜网流程: 分为SSB同步(包括MIB读取)和RMSI ...

  7. 因子分析数据_Excel数据分析案例:用Excel做因子分析

    有48位求职者信息,用15个维度来衡量求职者与岗位的适应度,具体数据信息如下: 由于变量之间的许多相关性很高,因此认为法官可能会混淆某些变量,或者某些变量可能是多余的.因此,进行了因素分析以确定较少的 ...

  8. jxl解析excel

    jxl解析excel ExcelOS工作 在进行实践前,我们需要对excel有一个大致的了解,excel文件由一个工作簿(Workbook)组成,工作簿由工作表(sheet)组成,每个工作表又由很多单 ...

  9. Delphi与Ole,Word,Excel,查找与替换等

    Delphi与Word之间的融合技术(下)zt 来自:yzhshi, 时间:2002-2-2 14:24:00, ID:902680 前面我就Delphi中调用Word写了一些,比较注重于具体实现,对 ...

  10. Java根据模板创建excel文件

    1.首先导入xml文件,src下建包xml,将student.xml文件放入此文件夹中 [html] view plain copy <excel id="student"  ...

最新文章

  1. ajax学习----json,前后端交互,ajax
  2. 信息抽取(二)花了一个星期走了无数条弯路终于用TF复现了苏神的《Bert三元关系抽取模型》,我到底悟到了什么?
  3. python交互窗口怎么才能不连着上一个程序_python实现启动一个外部程序,并且不阻塞当前进程...
  4. (转贴) C#编码标准--编码习惯
  5. python变量类型之间转换_Python常用数据类型之间的转换总结
  6. Yiic执行php脚本
  7. Android电视远程桌面,【当贝市场】教你使用小米电视远程控制Windows桌面
  8. 压缩感知算法_【封面论文】基于压缩感知算法的无透镜数字全息成像研究
  9. java 类的对象是什么意思_java中类和对象的概念
  10. 前端和后端哪个工资高?
  11. 机器学习笔记 - 什么是先验算法(Apriori Algorithm)?
  12. 《你不可不知的50个建筑学知识》之哥特式建筑 1
  13. 论文阅读翻译笔记之Incentives build robustness in BitTorrent
  14. Ecmascript 6
  15. 拷机测试需要多久_如何科学理解麒麟9000的拷机功耗?
  16. 浅谈恐怖漫画-恐怖的源头 恐怖漫画:漫画文化里的一枝奇葩
  17. 20180418小测
  18. 局域网设置共享文件夹及常见问题解决办法
  19. Python毕业设计开题报告职业推荐系统
  20. css基础语法与注释,简述CSS注释

热门文章

  1. 如何创建一个原始Mac OS镜像
  2. 解释外显子,内含子,CDS、cDNA、EST、mRNA、ORF间的区别
  3. WebMvcConfigurerAdapter已被废弃的解决方法
  4. skb_buff结构体解析
  5. Android文件或文件夹压缩成.zip格式的压缩包
  6. win10防火墙_教你一招,在Win10上设置允许应用通过Windows防火墙,非常简单
  7. 81192!请返航!
  8. Atcoder ARC093F : Dark Horse
  9. 2017CS231n李飞飞深度视觉识别笔记(二)——图像分类
  10. 系统聚类算法并绘制谱系图