@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文件的更多相关文章

  1. 史上最全的springboot导出pdf文件

    最近项目有一个导出报表文件的需求,我脑中闪过第一念头就是导出pdf(产品经理没有硬性规定导出excel还是pdf文件),于是赶紧上网查看相关的资料,直到踩了无数的坑把功能做出来了才知道其实导出exce ...

  2. 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 ---------------------------- ...

  3. (十一)SpringBoot导出excel文件

    一:添加POI依赖 <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-oox ...

  4. ASP.NET Core 导入导出Excel xlsx 文件

    ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件,EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出,可以运行在Windows, Li ...

  5. 【Easyexcel】java导入导出超大数据量的xlsx文件 解决方法

    解决方法: 使用easyexcel解决超大数据量的导入导出xlsx文件 easyexcel最大支持行数 1048576. 官网地址: https://alibaba-easyexcel.github. ...

  6. C# Aspose.Cells导出xlsx格式Excel,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”

    报错信息: 最近打开下载的 Excel,会报如下错误.(xls 格式不受影响) 解决方案: 下载代码(红色为新添代码) public void download() { string fileName ...

  7. asp.net NPOI导出xlsx格式文件,打开文件报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”

    NPOI导出xlsx格式文件,会出现如下情况: 点击“是”: 导出代码如下: /// <summary> /// 将datatable数据写入excel并下载 /// </summa ...

  8. 关于NPOI导出excel文件(xls和xlsx两种格式)提示格式不符的问题

    这两天在做导出excel文件的时候遇到这个问题 本来我导出的格式是xlsx格式的,但是下载得到的文件格式变成了xls, 一开始以为是返回的contenttype设置错了 return File(ms, ...

  9. springboot项目中文件的下载(解决中文乱码问题)

    最近使用springboot项目,一直以来文件都以英文格式存储,这次使用的是xls文件下载,文件名为中文的,特此记录下中文文件名的下载以及springboot中下载路径报错问题. 正文 在使用spri ...

随机推荐

  1. Python_获取cookie

    获取cookie from selenium import webdriver from selenium.webdriver.common.by import By # 定位 from seleni ...

  2. Xpath定位元素-一个例子

    前几天在群里面解决的问题,记录下来和大家分享 需要定位这个股份制企业 方法: # 首先需要单击下拉框弹出企业性质的下拉选项:然后用过Xpath定位元素 driver.find.element_by_c ...

  3. Java面试必会-微服务权限认证

    微服务身份认证方案 1. 单点登录(SSO) 这种方案意味着每个面向用户的服务都必须与认证服务交互,这会产生大量非常琐碎的网络流量和重复的工作,当动辄数十个微应用时,这种方案的弊端会更加明显. 2. ...

  4. Linux文件监控工具——inotify-tools

    举例: ip.txt内容如下: 10.1.1.11 root 123 10.1.1.22 root 111 10.1.1.33 root 123456 10.1.1.44 root 54321 写法1 ...

  5. [原题复现][2020i春秋抗疫赛] WEB blanklist(SQL堆叠注入、handler绕过)

    简介 今天参加i春秋新春抗疫赛 一道web没整出来 啊啊啊 好垃圾啊啊啊啊啊啊啊  晚上看群里赵师傅的buuoj平台太屌了分分钟上线 然后赵师傅还分享了思路用handler语句绕过select过滤.. ...

  6. 面试官:小伙子,说一说Java多线程有哪些创建方式吧

    第一种 继承Thread类 自定义类,继承Thread类,并重写run()方法. class MyThread1 extends Thread { @Override public void run( ...

  7. Kafka 内存管理类BufferPool

    基本上每个成熟的框架或者工具都有一套内存管理机制 BufferPool 是Kafka  用来管理内存的工具类         BufferPool内存管理包含2个部分,已用空间+可用空间(未申请空间+ ...

  8. Codeforces Round #677 (Div. 3) E、G题解

    E. Two Round Dances #圆排列 题目链接 题意 \(n\)(保证偶数)个人,要表演一个节目,这个节目包含两种圆形舞蹈,而每种圆形舞蹈恰好需要\(n/2\)个人,每个人只能跳一种圆形舞 ...

  9. Java蓝桥杯练习题——Huffman树

    Huffman树在编码中有着广泛的应用.在这里,我们只关心Huffman树的构造过程. 给出一列数{pi}={p0, p1, -, pn-1},用这列数构造Huffman树的过程如下: 找到{pi}中 ...

  10. Impala 3.3.0 源码编译安装

          最新编译Apache-impala 的心酸历程.大概花了10天才整好,极度的崩溃!!!由于国内的上网环境大家都懂的,访问国外的s3.amazonaws.com一些资源库的速度极其感人,尤其 ...