由于jQuery的ajax函数、及ajaxSubmit等函数的返回类型(dataType)只有xml、text、json、html等类型,没有“流”类型,故我们要实现ajax下载时,不能够使用相应的ajax函数进行文件下载。
于是只能使用构建表单的方式进行下载
$('#js-export').click(function () {
var allTableData = $('#mytab').bootstrapTable('getData');
var form = $("<form>");
form.attr('style', 'display:none');
form.attr('target', '');
form.attr('method', 'post');
form.attr('action', 'export_statistics');
var input1 = $('<input>');
input1.attr('type', 'hidden');
input1.attr('name', 'jsonParam');
input1.attr('value', JSON.stringify(allTableData));
$('body').append(form);
form.append(input1);
form.submit();
form.remove();
});
对应服务端代码为:
@PostMapping(value = "/export_statistics")
@ResponseBody
public void export_statistics(@RequestBody String jsonParam, HttpServletRequest request, HttpServletResponse response) throws Exception {
String fileName = System.currentTimeMillis() + "仪器统计表.xls";
Type type = new TypeToken<List<InstrumentTime>>() {}.getType();
List<InstrumentTime> instrumentTimeList = new Gson().fromJson(String.valueOf(jsonParam), type);
String[][] content = new String[instrumentTimeList.size()][];
for (int i = 0; i < instrumentTimeList.size(); i++) {
content[i] = new String[5];
InstrumentTime instrumentTime = instrumentTimeList.get(i);
content[i][0] = instrumentTime.getInstrumentName();
content[i][1] = instrumentTime.getConventionYemo();
content[i][2] = instrumentTime.getCount();
content[i][3] = instrumentTime.getInstrumentPerson();
System.out.println("content--->"+content[i][0]);
}
//创建HSSFWorkbook
HSSFWorkbook hf = InstrumentStatisticsExcelUtil.getHSSFWorkbook(content, null);
//响应到客户端
try {
this.setResponseHeader(response, fileName);
OutputStream os = response.getOutputStream();
hf.write(os);
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}