springboot 导出xlsx文件
@Override
public String downModelXlsFile(SxSourceReq param, HttpServletResponse response) {
//设置响应编码
response.setCharacterEncoding("GBK");
response.setContentType("multipart/form-data");
ImModSourceVo imModSourceVo = findDetail(param);
//ImModSourcePojo imModSourcePojo = imModSourcePojoMapper.get(param.getModSourceId());
if (imModSourceVo == null) {
return ReturnJsonFormatUntil.json(false, "该模板不存在!!!");
}
boolean isCustom = "2".equals(imModSourceVo.getModType());
//List<ImModSourceSheetPojo> modSourceSheetPojos = imModSourceSheetPojoMapper.findList(param);
if ((imModSourceVo.getList() == null || imModSourceVo.getList().size() == 0) && !isCustom) {
return ReturnJsonFormatUntil.json(false, "该模板,没有sheet信息!!!");
}
if (!isCustom) {
List<ImImpSourceSheetFactorPojo> factorPojoList = imImpSourceSheetFactorPojoMapper.findListBySheetIds(param);
Map<String,List<ImImpSourceSheetFactorPojo>> sheetFactorListMap = factorPojoList.stream().collect(Collectors.groupingBy(ImImpSourceSheetFactorPojo::getModSourceSheetId));
List<Map<String,Object>> sheetData = new ArrayList<>(imModSourceVo.getList().size());
Map<String, Object> sheetMap = null;
List<List<Map<String,Object>>> dataRowList = null;
ImModSourceSheetVo sheetParam = new ImModSourceSheetVo();
List<ImShowFactorColumnPojo> showFactorColumnPojos = getOrderImShowFactorColumnPojos(sheetParam);
for (ImModSourceSheetVo imModSourceSheetVo:imModSourceVo.getList()) {
sheetMap = new HashMap<>(3);
sheetMap.put("sheetIndex",imModSourceSheetVo.getSheetIndex());
sheetMap.put("sheetName",imModSourceSheetVo.getModSourceSheetName());
List<ImModTableUnitVo> tableUnitIndexList = imModSourceSheetVo.getList();
tableUnitIndexList.stream().sorted(Comparator.comparing(ImModTableUnitVo::getCoordinateY));
dataRowList = new ArrayList<>(tableUnitIndexList.size()+1);
List<Map<String,Object>> headers = new ArrayList<>();
List<ImModSourceSheetFactorVo> sheetFactorPojos = null;
if (ObjectsUtil.isNotEmpty(imModSourceSheetVo.getFactorList())) {
sheetFactorPojos = imModSourceSheetVo.getFactorList();
} else {
ListUtils.copyList(showFactorColumnPojos,sheetFactorPojos,ImModSourceSheetFactorVo.class);
}
sheetFactorPojos.stream().sorted(Comparator.comparing(ImImpSourceSheetFactorPojo::getOrderBy)); Map<String,Object> header = null;
Set<String> sortKeys = new HashSet<>();
for (ImImpSourceSheetFactorPojo sheetFactorPojo : sheetFactorPojos) {
header = new HashMap<>(1);
header.put("value",sheetFactorPojo.getFactorPropertyName());
sortKeys.add(sheetFactorPojo.getFactorName());
headers.add(header);
}
dataRowList.add(headers);
/* header.put("value","序号");
headers.add(header);
header = new HashMap<>(1);
header.put("value","指标名称");
headers.add(header);
header = new HashMap<>(1);
header.put("value","单位");
headers.add(header);
header = new HashMap<>(1);
header.put("value","本期上报值");
headers.add(header);
header = new HashMap<>(1);
header.put("value","备注说明");
headers.add(header);*/
List<Map<String,Object>> cellList = null;
Map<String,Object> cellMap = null;
if (ObjectsUtil.isNotEmpty(imModSourceSheetVo.getList())) {
for (ImModTableUnitVo imModTableUnitVo : tableUnitIndexList) {
cellList = new ArrayList<>(5);
cellMap = new HashMap<>(1);
for (String sortKey : sortKeys) {
if ("indexName".equals(sortKey)) {
cellMap.put("value",imModTableUnitVo.getValue());
} else if ("indexUnit".equals(sortKey)) {
if (ObjectsUtil.isNotEmpty(imModTableUnitVo.getIndexVo())) {
cellMap.put("value",imModTableUnitVo.getIndexVo().getIndexUnit());
} else {
cellMap.put("value","");
}
} else {
cellMap.put("value","");
}
cellList.add(cellMap);
}
/* cellMap.put("value",serial);
cellList.add(cellMap);
cellMap = new HashMap<>(1);
cellMap.put("value",imModTableUnitIndexVo.getIndexName());
cellList.add(cellMap);
cellMap = new HashMap<>(1);
cellMap.put("value",imModTableUnitIndexVo.getIndexUnit());
cellList.add(cellMap);
cellMap = new HashMap<>(1);
cellMap.put("value","");
cellList.add(cellMap);
cellMap = new HashMap<>(1);
cellMap.put("value",imModTableUnitIndexVo.getDescription());
cellList.add(cellMap);*/
//serial++;
dataRowList.add(cellList);
}
}
sheetMap.put("data",dataRowList);
sheetData.add(sheetMap);
}
String today = DateUtil.dateToStr(new Date());
String dirPath = IReportUtils.saveXlsFileToLocal(today); //输出文件到本地
String defaultFileName = DateUtil.getStringAllDate() + ".xls";
File file = new File(dirPath + "/" + defaultFileName);
String path = dirPath + File.separator + defaultFileName;
response.setHeader("Content-Disposition", "attachment;fileName=" + defaultFileName);
ByteArrayOutputStream byteArrayOutputStream = null;
try {
OutputStream os = response.getOutputStream();
log.info("导出开始!!!");
//outputStream = new BufferedOutputStream(new FileOutputStream(file));
byteArrayOutputStream = new ByteArrayOutputStream();
//ExcelUtil.write2OutputStream(os,sheetData);
//写文件
ExcelUtil.write2OutputStream(byteArrayOutputStream,sheetData);
response.setContentLength(byteArrayOutputStream.size());
ServletOutputStream outputStream = response.getOutputStream();
byteArrayOutputStream.writeTo(outputStream);
byteArrayOutputStream.close();
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("下载文件成功");
String results = ipAddress + path;
log.info(results);
return ReturnJsonFormatUntil.json(true, results);
} else {
if (ObjectsUtil.isEmpty(imModSourceVo.getFileId())) {
return ReturnJsonFormatUntil.json(false, "没有该模板文件!!");
}
ImFilePojo pojo = imFilePojoMapper.get(imModSourceVo.getFileId());
String filePath = "";
if (ObjectUtils.isEmpty(pojo)) {
log.error("查询的文件为空,不下载");
return ReturnJsonFormatUntil.json(false, "该文件id错误,无该文件!!!");
}
log.info("开始下载文件到本地");
String fileName = ObjectUtils.isEmpty(pojo.getFileName()) ? UuidUtils.uuid() : pojo.getFileName();
String path = System.getProperty("user.dir");
try {
if(!FtpUtil.downloadFileJlf(1,response,
ftpConstants.getFTP_HOST_INDEX(),
ftpConstants.getFTP_PORT_INDEX(),
ftpConstants.getFTP_USER_INDEX(),
ftpConstants.getFTP_PASSWORD_INDEX(),
pojo.getFilePath(),
pojo.getFileName(),
"",
pojo.getFileName()
)
){
return ReturnJsonFormatUntil.json(false, ResultConstants.DOWNLOAD_FALURE);
}
//下载路径
//path = today + "_report/" + defaultFileName;
log.info("导出成功!!!");
} catch (Exception e) {
log.error("下载失败+++++++++++++++" + fileName);
log.error(e.getMessage());
e.printStackTrace();
return filePath;
}
log.info("下载文件成功");
String results = ipAddress + path;
log.info(results);
return ReturnJsonFormatUntil.json(true, results);
}
}
首先开始设置响应格式
response.setCharacterEncoding("GBK");
response.setContentType("multipart/form-data");
然后设置响应文件名称
String today = DateUtil.dateToStr(new Date());
String dirPath = IReportUtils.saveXlsFileToLocal(today); //输出文件到本地
String defaultFileName = DateUtil.getStringAllDate() + ".xls";
File file = new File(dirPath + "/" + defaultFileName);
String path = dirPath + File.separator + defaultFileName;
response.setHeader("Content-Disposition", "attachment;fileName=" + defaultFileName);
导出文件到本地,并且把输出流写入给response
ByteArrayOutputStream byteArrayOutputStream = null;
try {
OutputStream os = response.getOutputStream();
log.info("导出开始!!!");
//outputStream = new BufferedOutputStream(new FileOutputStream(file));
byteArrayOutputStream = new ByteArrayOutputStream();
//ExcelUtil.write2OutputStream(os,sheetData);
ExcelUtil.write2OutputStream(byteArrayOutputStream,sheetData);
response.setContentLength(byteArrayOutputStream.size());
ServletOutputStream outputStream = response.getOutputStream();
byteArrayOutputStream.writeTo(outputStream);
byteArrayOutputStream.close();
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
log.info("下载文件成功");
String results = ipAddress + path;
log.info(results);
return ReturnJsonFormatUntil.json(true, results);
ftp下载xlsx文件代码为
public static boolean downloadFileJlf(int fileType, HttpServletResponse response, String host, int port, String username, String password, String remotePath,
String fileName, String localPath,String saveAsFileName) { int count=0; FTPClient ftpClient = new FTPClient();
ftpClient.setControlEncoding("GBK");
response.setContentType("multipart/form-data");
log.info(host + ":" + port + ":" + username + ":" + ":" + password + ":" + remotePath + ":" + fileName + ":" + localPath + ":" + saveAsFileName +":" + fileType);
//
// FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
// conf.setServerLanguageCode("zh");
// ftpClient.configure(conf);
String fileLastName=""; try {
int reply;
ftpClient.connect(host, port);
ftpClient.login(username, password);
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return false;
}
/* ftpClient.changeWorkingDirectory(remotePath);//转移到FTP服务器目录
FTPFile[] fs = ftpClient.listFiles();
for (int i = 0; i < fs.length; i++) {
if (fs[i].getName().trim().equals(fileName)) {
if (fileType==1){
fileLastName=getFileNameNoEx(1,fs[i].getName());
}
saveAsFileName = new String(saveAsFileName.getBytes("GB2312"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName);
OutputStream os = response.getOutputStream();
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(fs[i].getName(), os);
os.flush();
os.close();
count++;
break;
}
}
*/
// FTPFile[] files = ftpClient.listFiles(remotePath);
saveAsFileName = new String(saveAsFileName.getBytes("GBK"), "ISO-8859-1");
response.setHeader("Content-Disposition", "attachment;fileName=" + saveAsFileName); OutputStream os = response.getOutputStream();
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.retrieveFile(remotePath+"/"+fileName, os);
os.flush();
os.close();
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
ioe.printStackTrace();
return false;
}
}
} return true;
}
由于xlsx文件比较特殊,如果还是下载失败,最后一种笨方法就是把文件下载到服务器本地,每天把文件放入指定文件夹,返回一个可以访问文件的路径,让用户从本地直接访问路径直接下载文件,第二天如果还有人下载文件,创建新文件夹,删除
昨天的旧文件夹即可,该方法只适用于下载文件比较少的情况,如果文件下载量太大,还是老老实实研究一下怎么下载xlsx文件吧!!!
@font-face { font-family: "yourDictFontAwesome"; src: url("chrome-extension://nnijdpomjcmgahgjcdgimjldkopghaef/lib/fontawesome-webfont.ttf") format("truetype"); font-weight: normal; font-style: normal }
@font-face { font-family: "yourDictFontAwesome"; src: url("chrome-extension://nnijdpomjcmgahgjcdgimjldkopghaef/lib/fontawesome-webfont.ttf") format("truetype"); font-weight: normal; font-style: normal }
springboot 导出xlsx文件的更多相关文章
- 史上最全的springboot导出pdf文件
最近项目有一个导出报表文件的需求,我脑中闪过第一念头就是导出pdf(产品经理没有硬性规定导出excel还是pdf文件),于是赶紧上网查看相关的资料,直到踩了无数的坑把功能做出来了才知道其实导出exce ...
- Microsoft SQL Server 17导出xlsx文件时报错:The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine. (System.Data)
导出数据时报错: 如果你是导出office 2007格式 TITLE: SQL Server Import and Export Wizard ---------------------------- ...
- (十一)SpringBoot导出excel文件
一:添加POI依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-oox ...
- ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...
- 【Easyexcel】java导入导出超大数据量的xlsx文件 解决方法
解决方法: 使用easyexcel解决超大数据量的导入导出xlsx文件 easyexcel最大支持行数 1048576. 官网地址: https://alibaba-easyexcel.github. ...
- C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
报错信息: 最近打开下载的 Excel,会报如下错误.(xls 格式不受影响) 解决方案: 下载代码(红色为新添代码) public void download() { string fileName ...
- asp.net NPOI导出xlsx格式文件,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
NPOI导出xlsx格式文件,会出现如下情况: 点击“是”: 导出代码如下: /// <summary> /// 将datatable数据写入excel并下载 /// </summa ...
- 关于NPOI导出excel文件(xls和xlsx两种格式)提示格式不符的问题
这两天在做导出excel文件的时候遇到这个问题 本来我导出的格式是xlsx格式的,但是下载得到的文件格式变成了xls, 一开始以为是返回的contenttype设置错了 return File(ms, ...
- springboot项目中文件的下载(解决中文乱码问题)
最近使用springboot项目,一直以来文件都以英文格式存储,这次使用的是xls文件下载,文件名为中文的,特此记录下中文文件名的下载以及springboot中下载路径报错问题. 正文 在使用spri ...
随机推荐
- jm8.6编解码器概述
自己在学习h264的路上,欢迎讨论交流. 前段时间研究JM出品的h264编码器,代码实在看不下去,因此换了个角度来研究诸多算法--逆向方式(解码),本系列文章记录一些遇到的东西和思考. 1. JM介绍 ...
- Centos7升级内核后无法启动解决办法
前言 这个问题存在有一段时间了,之前做的centos7的ISO,在进行内核的升级以后就存在这个问题: 系统盘在板载sata口上是可以正常启动新内核并且能识别面板硬盘 系统盘插在面板口上新内核无法启动, ...
- 多线程实现socketserver练习
1.server import socket from threading import Thread def my_socketserver(conn, addr): conn.send(b'hel ...
- ASP.NET Core管道详解[2]: HttpContext本质论
ASP.NET Core请求处理管道由一个服务器和一组有序排列的中间件构成,所有中间件针对请求的处理都在通过HttpContext对象表示的上下文中进行.由于应用程序总是利用服务器来完成对请求的接收和 ...
- 精尽MyBatis源码分析 - MyBatis 的 SQL 执行过程(一)之 Executor
该系列文档是本人在学习 Mybatis 的源码过程中总结下来的,可能对读者不太友好,请结合我的源码注释(Mybatis源码分析 GitHub 地址.Mybatis-Spring 源码分析 GitHub ...
- Camtasia绿幕素材的视频合成
随着科技和互联网的快速发展,让越来越多的人喜欢上了视频的各项制作,那么怎么让两个视频进行合成并一起播放呢?操作很简单,下面来讲解具体的操作步骤.小编选用的是Camtasia2019版本的视频编辑软件进 ...
- 浅析Nginx与Apache的区别
Nginx相对于Apache的优势: 1.轻量级,采用C进行编写,同样的web服务,会占用更少的内存及资源 2.抗并发,nginx以epoll and kqueue作为开发模型,处理请求是异步非阻塞的 ...
- thinkphp3.2 添加自定义类似__ROOT__的变量
1 thinkphp3.2 添加自定义类似__ROOT__的变量 2 3 在config.php文件中 4 return array( 5 '' => '', 6 'TMPL_PARSE_STR ...
- python的os命令
os常用命令 os.sep:取代操作系统特定的路径分隔符 os.name:指示你正在使用的工作平台.比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'. os.g ...
- 解决-Chrome插件安装时程序包无效:"CRX_HEADER_INVALID"
最近安装新的谷歌插件出现 :程序包无效:"CRX_HEADER_INVALID" 原因如下: 在地址栏输入chrome://settings/help 如果,你的 Chrome 浏 ...