springboot导出excel工具类

try{
//捕获内存缓冲区的数据,转换为字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
workbook.write(out);
//获取内存缓冲中的数据
byte[] content = out.toByteArray();
//将字节数据转化为输入流
InputStream in = new ByteArrayInputStream(content);
//通过调用reset()方法可以重新定位
response.reset();
//JSONP 解决跨域问题
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Allow-Methods","GET,POST,PUT,DELETE,OPTIONS");
response.addHeader("Access-Control-Allow-Headers", "WWW-Authenticate,Authorization,Set-Cookie," +
"X-Requested-With,Accept-Version,Content-Length,Content-Type,Date,X-Api-Version,name");
response.addHeader("Access-Control-Allow-Credentials", "true");
// response.setContentType("application/octet-stream");
//如果文件名是英文名不需要加编码格式,如果是中文名需要添加"ios-8859-1"防止乱码
response.setHeader("Content-Disposition", "attachment;filename=" +
new String((fileName + ".xls").getBytes("gb2312"), "iso-8859-1"));
response.setHeader("Content-Length", "" + content.length);
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(in);
BufferedOutputStream bos = new BufferedOutputStream(outputStream);
byte[] buff = new byte[8192];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))){
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
outputStream.flush();
outputStream.close();

}catch (IOException ex){
ex.printStackTrace();
}

关注公众号“大模型全栈程序员”回复“小程序”获取1000个小程序打包源码。更多免费资源在http://www.gitweixin.com/?p=2627

发表评论

邮箱地址不会被公开。 必填项已用*标注