@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. Java初始化静态变量的时间顺序

    1. 开始吧! 今天,我们来探讨交流下静态变量初始化过程.Java虚拟机在类加载期间也同样遵循这个过程. 2. 初始化过程 在较高的层次上,JVM执行以下步骤: 首先,加载并链接类.然后,这个过程的& ...

  2. Django启动服务的流程

    我晕,启动个服务浪费快一个小时的时间,记录下步骤吧. 1.D:\django\newworld>python manage.py runserver Performing system chec ...

  3. appium-appium的等待时间

    #三种appium设置等待时间的方法 #第一种 sleep(): 设置固定休眠时间. python 的 time 包提供了休眠方法 sleep() , 导入 time包后就可以使用 sleep()进行 ...

  4. CTF-WEB-HCTF 2018 Warmup

    题目链接 攻防世界-Warmup 解题思路 [原题复现]HCTF 2018 Warmup(文件包含)

  5. Python学习第三天 --- 分支、循环、条件、枚举

    1.表达式: 表达式(Expression)是运算符(operator)和操作数(operand)所构成的序列. 2.表达式的优先级: 3.python的注释: #单行注释 ''' 多行注释 ''' ...

  6. 面经分享!蚂蚁金服三面被拒,重拾起鼓四面猿辅导成功拿下offer!

    前言 一直有小伙伴要我分享面经,说自己想面互联网公司,无奈经验太少想多看看其他人是怎么面的.我这两天刚好和一个刚拿到猿辅导offer的朋友吃了个饭,他向我说了说自己的面试经历.粉丝朋友是末流211毕业 ...

  7. 攻克solo第六课(大调音阶与真的爱你)

    在本期文章中,笔者将通过guitar pro7和大家分享大调音阶的知识. 不知道大家有没有试着使用my song book里面的谱子,反正笔者是觉得赚大了,并且找了囊括民谣.爵士到摇滚在内不同风格的谱 ...

  8. python中操作数据库

    python中要操作数据库,要使用该数据库在python中对应的驱动库,本文介绍python操作mysql数据库 1.首先安装pymysql 2.导入库 3.建立连接 4.建立游标 5.发起请求 6. ...

  9. Shamir秘密共享方案 (Python)

    Shamir's Secret Sharing scheme is an important cryptographic algorithm that allows private informati ...

  10. SpringBoot 实现微信推送模板

    导读 由于最近手头上需要做个Message Gateway,涉及到:邮件(点我直达).短信.公众号等推送功能,网上学习下,整理下来以备以后使用. 添加依赖 在SpringBoot项目中添加依赖 < ...