导出Excel功能
从服务端到浏览器的简单处理, 仅供参考
服务端定义一个导出功能的关键代码
Java 定义一个export的功能函数,以下为关键代码(接口中的一部分处理逻辑):
@Override
public byte[] export(String startdate, String enddate, Integer type, String name,
HttpServletResponse response) {
// other logic omitted here ...
// set response args,it used for open download
response.reset();
response.setContentType("application/vnd.ms-excel;charset=utf-8");
try {
response.setHeader("Content-Disposition", "attachment;filename=" +
new String((name+ ".xls").getBytes(), "iso-8859-1"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
workList.write(output); // write
} catch (IOException e) {
e.printStackTrace();
}
return output.toByteArray();
}
前端处理
- 方式1:使用ng1实现,在自定义指令中来通过接口接收数据流 [ 存在兼容问题的方式 ]
指令如下:
angular.module('yourNgApp')
.directive('sysExport', function ($http, $document) {
return {
templateUrl: "app/system/export/export.directive.html",
restrict: 'EA',
replace: true,
scope: {
item: '='
},
link: function (scope, element) {
// 访问请求的函数
function getExport(postData) {
// 拼出自己的url
var url = '/api/course/export?startdate=' +
postData.startdate + '&enddate=' + postData.enddate +
'&type=' + postData.type + '&name=' + postData.name;
// 注意下面的responseType 一定要有哦!
var finalPostData = {
url: url,
method: 'POST',
responseType: "arraybuffer",
headers: {'Content-type': 'application/json'}
};
$http(finalPostData)
.success(function (data) {
var blob, fileName, blobArgs;
blobArgs = {type: 'application/vnd.ms-excel application/x-excel'};
blob = new Blob([data], blobArgs);
var a = $document[0].createElement('a');
a.download = postData.name + '.xls';
a.href = URL.createObjectURL(blob);
a.click();
})
.error(function (e) {
console.log(e);
});
}
element.on('click', function () {
getExport(scope.item);
});
}
};
});
- 至此可实现通过指令的点击事件来下载excel格式了。
- 因为导出功能多用于后台管理,适用性不是很普遍,所以兼容问题可协商,所以前台使用了Blob对象。
- 为了节约服务器资源可通过此种方式通过点击来下载,而不是将导出的文件单独存放到服务器上通过返回excel所在的url地址来进行下载。
2)方式2:直接通过a链接访问,[兼容性好]
示例:
<a href="/api/course/export?startdate={{cl.startdate}}&enddate={{cl.enddate}}&type={{cl.type}}&name={{cl.name}}" class="btn btn-success">导出</a>
扩展
- mine 类型: http://www.w3school.com.cn/media/media_mimeref.asp
- Blob的用法和兼容性:https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
- Java 端用于导出excel的工具 poi : http://poi.apache.org/ https://github.com/apache/poi
- 关于 a.download以及它的兼容性 : http://www.w3school.com.cn/tags/att_a_download.asp
- 关于 URL.createObjectURL : https://developer.mozilla.org/zh-CN/docs/Web/API/URL/createObjectURL
总结
上面前端用到的都是一些H5高级API 适用性不是很高, 但也临时解决了一些问题,只作为尝试 :)
通过a链接的方式请求, 直接在服务器端完成文件的操作,点击后直接下载,兼容良好,但不适合大文件的传输下载。