pom.xml

        <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.9</version>
</dependency>
ExcelUtil.java
package com.zjjw.cases.web;

import com.alibaba.nacos.common.util.UuidUtils;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
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.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.springframework.util.StringUtils; @Slf4j
public class ExcelUtil { private static Integer MAXROWS = 1048000; public synchronized static <Ty> void outfile(HttpServletResponse response, Map<String, String> map, String sheetname, List<Ty> list) throws Exception {
String uuid = UuidUtils.generateUuid();
log.info("id:{},执行导出开始",uuid);
//创建poi导出数据对象
SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(1000);
//创建全局样式
CellStyle cellStyle = sxssfWorkbook.createCellStyle();
cellStyle.setFillForegroundColor((short) 10);
cellStyle.setBorderBottom(CellStyle.BORDER_NONE); //下边框
cellStyle.setBorderLeft(CellStyle.BORDER_NONE);//左边框
cellStyle.setBorderTop(CellStyle.BORDER_NONE);//上边框
cellStyle.setBorderRight(CellStyle.BORDER_NONE);//右边框
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); //垂直居中
//cellStyle.setWrapText(true);//自动换行
Font font = sxssfWorkbook.createFont();
font.setFontName("宋体");//设置字体
short pintSize = 10;
font.setFontHeightInPoints(pintSize);//设置字体大小
// font.setBold(true);//加粗
cellStyle.setFont(font);
int integer = list.size();
if (MAXROWS<integer) {
throw new RuntimeException("数据行数超过excel最大数据行数!");
}
if (integer > 0) {
//数据量过大分批拉取
int k = 0;
//一个sheet最大行数
final int pageNum = 500000;
double count = deciMal(integer, pageNum);
double num = Math.ceil(count);
int j = 1;
while (num != 0) {
String newsheetname = sheetname + j;
if (num == 1) {
List<Ty> subList = list.subList(k, integer);
setData(map, newsheetname, sxssfWorkbook, cellStyle, pintSize, subList);
} else {
List<Ty> subList = list.subList(k, k + pageNum);
k = k + pageNum;
// 创建sheet页
setData(map, newsheetname, sxssfWorkbook, cellStyle, pintSize, subList);
}
num--;
j++;
}
} // 下载导出
String filename = sheetname + getNowTime();
//创建一个输出流
OutputStream outputStream = null;
try {
// 设置头信息
response.setCharacterEncoding("UTF-8");
response.setContentType("application/vnd.ms-excel");
//一定要设置成xlsx格式
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename + ".xlsx", "UTF-8"));
outputStream = response.getOutputStream();
//写入数据
sxssfWorkbook.write(outputStream);
outputStream.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != outputStream) {
outputStream.close();
}
} log.info("id:{},执行导出结束",uuid);
} private static double deciMal(int top, int below) {
float f = (float)top/below;
double result = new BigDecimal(f).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
return result;
} private static <Ty> void setData(Map<String, String> map, String newsheetname, SXSSFWorkbook sxssfWorkbook, CellStyle cellStyle, short pintSize, List<Ty> subList) {
// 创建sheet页
SXSSFSheet sheet = (SXSSFSheet) sxssfWorkbook.createSheet(newsheetname);
int size = map.size() - 1;
/** 合并表头
CellRangeAddress region = new CellRangeAddress(0, 0, (short) 0, (short) size);
//参数1:起始行 参数2:终止行 参数3:起始列 参数4:终止列
sheet.addMergedRegion(region);
SXSSFRow headTitle = sheet.createRow(0);
SXSSFCell cellHeadTitle = headTitle.createCell(0);
cellHeadTitle.setCellValue(newsheetname);
cellHeadTitle.setCellStyle(cellStyle);
//创建表头
SXSSFRow headRow = sheet.createRow(1);*/
Row headRow = sheet.createRow(0);
//设置excel表头
int i = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
String mapKey = entry.getKey();
String[] split = mapKey.split("-");
mapKey = split[0];
//设置表头宽度
if (split.length > 1) {
int titlewidth = Integer.parseInt(split[1]);
titlewidth = titlewidth * pintSize * 30;
sheet.setColumnWidth(i, titlewidth);
}
Cell cell = headRow.createCell(i);
cell.setCellValue(mapKey);
cell.setCellStyle(cellStyle);
i++;
} // 遍历上面数据库查到的数据
for (Ty t : subList) {
Row dataRow = sheet.createRow(sheet.getLastRowNum() + 1);
Map<String, Object> data = null;
if (t instanceof Map) {
data = (Map<String, Object>) t;
} else {
data = object2Map(t);
}
//设置excel表头
int j = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
String mapValue = entry.getValue();
Cell cell = dataRow.createCell(j);
Object obj = data.get(mapValue);
String value = "";
if (!StringUtils.isEmpty(obj)) {
value = value + obj;
}
cell.setCellValue(value);
cell.setCellStyle(cellStyle);
j++;
}
}
} private static String getNowTime() //获取当前系统时间并格式化
{
System.setProperty("user.timezone", "GMT+08");
Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH) + 1;
int date = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
// String nowTime = year + "-" + month + "-" + date + "-" + hour + "-" + minute + "-" + second;
String nowTime = year + "" + month + "" + date + "" + hour + "" + minute + "" + second;
return nowTime;
} /**
* 实体对象转成Map
*
* @param obj 实体对象
* @return
*/
private static Map<String, Object> object2Map(Object obj) {
Map<String, Object> map = new HashMap<String, Object>();
if (obj == null) {
return map;
}
Class clazz = obj.getClass();
Field[] fields = clazz.getDeclaredFields();
try {
for (Field field : fields) {
field.setAccessible(true);
map.put(field.getName(), field.get(obj));
}
} catch (Exception e) {
log.error("object2Map方法异常",e);
}
return map;
} /**
* Map转成实体对象
*
* @param map map实体对象包含属性
* @param clazz 实体对象类型
* @return
*/
private static <T> T map2Object(Map<String, Object> map, Class<T> clazz) {
if (map == null) {
return null;
}
T obj = null;
try {
obj = clazz.newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for (Field field : fields) {
int mod = field.getModifiers();
if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
continue;
}
field.setAccessible(true);
String filedTypeName = field.getType().getName();
if (filedTypeName.equalsIgnoreCase("java.util.date")) {
String datetimestamp = String.valueOf(map.get(field.getName()));
if (datetimestamp.equalsIgnoreCase("null")) {
field.set(obj, null);
} else {
field.set(obj, new Date(Long.parseLong(datetimestamp)));
}
} else {
field.set(obj, map.get(field.getName()));
}
}
} catch (Exception e) {
log.error("map2Object方法异常",e);
}
return obj;
} }

springboot poi的更多相关文章

  1. SpringBoot+POI报表批量导出

    由于servletResponse 获取的输出流对象在一次请求中只能输出一次,所以要想实现批量导出报表,需要将excel文件打包成zip格式然后输出. 好了,废话不多说,上代码. 1. 首先,需要导入 ...

  2. 使用poi进行数据的导出Demo

    这是本人在项目中遇到了一个导出数据时,如果该条数据中包含汉字,就会出现excel单元格的大小与期望的样式不一样,也是查找了半天,也没有发现哪里出的问题. 现将一个小Demo奉献在这里,可以在遇到使用p ...

  3. SpringBoot加Poi仿照EasyPoi实现Excel导出

    POI提供API给Java程序对Microsoft Office格式档案读和写的功能,详细功能可以直接查阅API,因为使用EasyPoi过程中总是缺少依赖,没有搞明白到底是什么坑,索性自己写一个简单工 ...

  4. 基于springboot跟poi封装的最便捷的excel导出

    发布时间:2018-11-15   技术:springboot1.5.6 + maven3.0.5 + jdk1.8   概述 Springboot最便捷的Excel导出,只需要一个配置文件即可搞定 ...

  5. SpringBoot图文教程9—SpringBoot 导入导出 Excel 「Apache Poi」

    有天上飞的概念,就要有落地的实现 概念十遍不如代码一遍,朋友,希望你把文中所有的代码案例都敲一遍 先赞后看,养成习惯 SpringBoot 图文教程系列文章目录 SpringBoot图文教程1「概念+ ...

  6. SpringBoot文件上传与POI的使用

    1.使用springboot上传文件 本文所要源码在一个项目中,源码:https://github.com/zhongyushi-git/springboot-upload-download.git. ...

  7. Springboot+vue前后端分离项目,poi导出excel提供用户下载的解决方案

    因为我们做的是前后端分离项目 无法采用response.write直接将文件流写出 我们采用阿里云oss 进行保存 再返回的结果对象里面保存我们的文件地址 废话不多说,上代码 Springboot 第 ...

  8. SpringBoot集成文件 - 集成POI之Excel导入导出

    Apache POI 是用Java编写的免费开源的跨平台的 Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能.本文主要介绍通过Spr ...

  9. SpringBoot集成文件 - 如何使用POI导出Word文档?

    前文我们介绍了通过Apache POI导出excel,而Apache POI包含是操作Office Open XML(OOXML)标准和微软的OLE 2复合文档格式(OLE2)的Java API.所以 ...

随机推荐

  1. python调用c/c++时传递结构体参数

    背景:使用python调用linux的动态库SO文件,并调用里边的c函数,向里边传递结构体参数.直接上代码 //test1.c # include <stdio.h> # include ...

  2. html script生成二维码

    <div class="code" align="center"> <p >手机端扫描以下二维码直接观看(支持安卓Android/苹果i ...

  3. laravel 使用PhantomMagick导出pdf ,在Linux下安装字体

    git项目地址:https://github.com/anam-hossain/phantommagick sudo apt-get -y install fontconfig xfonts-util ...

  4. IntelliJ IDEA 配置 Hadoop 源码阅读环境

    1.下载安装IDEA https://www.jetbrains.com/idea/download/#section=windows 2.下载hadoop源码 https://archive.apa ...

  5. Vue中使用JSX语法

    一 项目结构 二 App组件 <template> <div id="app"> <fruit/> </div> </temp ...

  6. cocos2dx基础篇(10) 按钮控件CCControlButton

    [3.x] (1)去掉 “CC” (2)对象类 CCObject 改为 Ref (3)按钮事件回调依旧为 cccontrol_selector ,没有使用 CC_CALLBACK_2 (4)按钮状态  ...

  7. 转 appium grid分布式环境搭建

    https://blog.csdn.net/ljl6158999/article/details/80803239 说起grid,了解selenium的人肯定知道,他就是分布式的核心.原理是简历中心h ...

  8. 深入IO 想学必看!受益匪浅哦~

    一:IO流概述 IO流简单来说就是Input和Output流,IO流主要是用来处理设备之间的数据传输,Java对于数据的操作都是通过流实现,而Java用于操作流的对象都在IO包中. 分类: 按操作数据 ...

  9. .Net Core - 使用Supervisor进行托管部署

    环境 CentOS 7 x64,详见 安装CentOS7虚拟机 .Net Core 2.1.801 详见 CentOS 7 下安装.NET Core SDK 2.1 ftp  详见  CentOS7 ...

  10. 跟风Manacher算法整理

    这是上上周天机房一位神仙讲的,\(gu\)了这么久才来整理\(w\),神仙讲的基本思路已经全都忘记了,幸好的是神仙写了\(blog\),吹爆原博浅谈\(Manacher\)算法,以及原博神仙\(ych ...