导入包,本来自己也不想用poi处理的,怎奈不知道为什么自己用流导出总是会报错不可读,所以还是简单点吧:
<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.9</version></dependency>
工具代码:
public class FileUtil {public static void download(String filename, HttpServletResponse res) {String filePath = "./template/" + filename;try (OutputStream os = res.getOutputStream(); InputStream bis = new BufferedInputStream(new ClassPathResource(filePath).getInputStream())){// 设置信息给客户端不解析String type = new MimetypesFileTypeMap().getContentType(filename);// 设置content-type,即告诉客户端所发送的数据属于什么类型res.setContentType(type);// 设置编码String name = URLEncoder.encode(filename, "UTF-8");// 设置扩展头,当Content-Type 的类型为要下载的类型时 , 这个信息头会告诉浏览器这个文件的名字和类型。res.setHeader("Content-Disposition", "attachment;filename=" + name);XSSFWorkbook workbook = new XSSFWorkbook(bis);workbook.write(os);}catch (Exception e){e.printStackTrace();}}}
重点是这句:XSSFWorkbook workbook = new XSSFWorkbook(bis);
文件所在位置:
关注公众号获取更多内容,有问题也可在公众号提问哦:
强哥叨逼叨
叨逼叨编程、互联网的见解和新鲜事