页面
、
Controller
/**
* @Author 张满
* @Description 下载校友示例表格
* @Date 2019/8/15 21:31
* @Param [request, response]
* @return void
**/
@RequestMapping("/downloadDemo")
public void downloadDemo(HttpServletRequest request, HttpServletResponse response) throws Exception{
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
String fileName = "示例样表.xlsx";
fileName=new String(fileName.getBytes(),"ISO-8859-1");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
InputStream fis=null;
OutputStream os=null;
try {
//读取文件
File file=null;
String sys = System.getProperty("os.name");
if(sys.toLowerCase().startsWith("win")){
//在开发环境下这么读取文件,在生产环境中不能这么读取
file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "static/download/示例样表.xlsx");
fis=new FileInputStream(file);
//写入输出流返回客户端
os = response.getOutputStream();
int len = -1;
byte[] b = new byte[1024*10];
while ((len=fis.read(b))!=-1){
os.write(b,0,len);
}
os.flush();
}else {
//在生产环境下 path 不以’/'开头时默认是从此类所在的包下取资源,以’/'开头则是从ClassPath根下获取
//这种方式打成jar包后,文件会被损坏!!!使用poi解决
fis = this.getClass().getResourceAsStream("/static/download/示例样表.xlsx");
//HSSFWorkbook:是操作Excel2003以前(包括2003)的版本,扩展名是.xls
//XSSFWorkbook:是操作Excel2007的版本,扩展名是.xlsx
XSSFWorkbook workbook = new XSSFWorkbook(fis);
os = response.getOutputStream();
workbook.write(os);
workbook.close();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(os!=null){
os.close();
}
if(fis!=null){
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
资源
pom
<!--poi的依赖-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.11</version>
</dependency>
<dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.11</version>
</dependency>
问题
在本地测试一切正常,但是放在服务器上就会发生问题,下载的excel表格显示:文件损坏,无法打开!
经过排查。我发现使用wps就可以打开文件。使用微软的excel就不行
解决方法
这其实是excel对网络上下载的文件的安全性控制。
解决方法一:
右键点击文件,查看属性,勾选“解除锁定”,点击确定,即可解决。
解决方法二:
将以上三个选项都不选中,即可解决
方法一相较与方法二简单,但是只能解决一次,每次都要这么点,方法二设置后,以后就可以不用设置。
获得也可以使用wps而不使用excel。