@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. 极客mysql13

    1:为啥删除了表的一半数8据,表文文件大小没变化?因为delete 命令其实只是把记录的位置,或者数据页标记为了"可复用",但磁盘文件的大小是不会变的.也可以认为是一种逻辑删除,所 ...

  2. 一键SSH连接 = SSH密钥登陆 + WindowsTerminal

    本文记录如何利用SSH密钥登录和WindowsTerminal/FluentTerminal实现一键SSH连接 目录 一.在本地生成SSH密钥对 二.在远程主机安装公钥 三.在远程主机打开密钥登陆功能 ...

  3. 从头学起Verilog(一):组合逻辑基础与回顾

    引言 该部分主要回顾了本科时数字电路中组合逻辑电路部分,内容相对简单和基础. 内容主要包括:布尔代数相关知识,卡诺图,最大项与最小项,竞争和冒险以及一些常见模块 数字电路中的逻辑 组合逻辑:输出可以表 ...

  4. 四:Redis五大数据类型

    Redis的五大数据类型 1.string(字符串) string是Redis最基本的类型,你可以理解成与menmcached一模一样的类型,一个key对应一个value string类型是二进制安全 ...

  5. rbd-mirror配置指南-单向备份

    前言 RBD 的 mirroring 功能将在Jewel中实现的,这个Jewel版本已经发布了很久了,这个功能已经在这个发布的版本中实现了,本来之前写过一篇文章,但是有几个朋友根据文档配置后,发现还是 ...

  6. Dubbo 服务导出-Version2.7.5

    1.源码分析 1.1分析服务导出入口 当容器为spring是dubbo会为容器注册两个监听器:DubboLifecycleComponentApplicationListener和DubboBoots ...

  7. 冷门的HTML - tabindex 的作用

    冷门的HTML - tabindex 的作用 HTML 的 tabindex 属性开发过程中一般不会使用到,最近开发中有个需求兼顾富交互,便总结了一下.本篇文章同时收录在我的[前端知识点]中,Gith ...

  8. ABBYY FineReader 与资源管理器的集成使用

    ABBYY FineReader 15(Windows系统)与 Windows 资源管理器的集成使用后,在不打开软件的情况下,可通过右击启动快捷菜单开启. 通过与Windows资源管理器的集成,用户可 ...

  9. Comparator比较器

    Comparator比较器 简介 为什么写? comparator 是javase中的接口,位于java.util包下,该接口抽象度极高,有必要掌握该接口的使用 大多数文章告诉大家comparator ...

  10. 返回当前类所有常量的Key=>value 集合

    <?php class Test { const A = '1'; const B = '2'; const C = '3'; const D = '4'; const E = '5'; con ...