其中关键的设置是
<struts>
<package name="struts2" extends="struts-default">
<action name="FileDownload" class="com.struts2.filedownload.FileDownload">
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="contentDisposition">attachment;fileName="${fileName}"</param>
<param name="inputName">downloadFile</param>
<param name="bufferSize">1024</param>
</result>
</action>
</package>
</struts>
web-SpringMvc等非struts框架中弹出
在response中设置头
response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes()));
OutputStream os= new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
os.write(buffer);
os.flush();
os.close();
例如:
jsp页面 使用js 提交 post form
$(document).ready(function() {
var $searchForm = $('#search_form').on('submit',function(){
$dt.DataTable().searchEx( {} ).draw();
return false;
}).on('click', 'button.export', function(){
var searchData={};
searchData.search=$('#search_form').formGet();
console.log(searchData);
post('/order/list/export',searchData);
});
function post(URL, PARAMS) {
var temp = document.createElement("form");
temp.action = URL;
temp.method = "post";
temp.style.display = "none";
for (var x in PARAMS.search) {
var opt = document.createElement("textarea");
if(x=="id"||x=="expressNumber"||x=="payStatus"){
opt.name = x;
opt.value = PARAMS.search[x];
temp.appendChild(opt);
}
}
document.body.appendChild(temp);
temp.submit();
}
}
后端接受参数后查询出数据,把生成的excel写入excel,返回文件流
@RequestMapping("/list/export")
public Object export(@RequestParam String id,@RequestParam String expressNumber,@RequestParam String payStatus,HttpServletResponse response) {
PagerRequest<Map> req=new PagerRequest<Map>();
req.setLength(0);
req.setOffset(0);
HashMap<String, String> search=new HashMap<String, String>();
search.put("id", id);
search.put("expressNumber", expressNumber);
search.put("payStatus", payStatus);
req.setSearch(search);
List<Order> orders = new ArrayList<Order>();
if (req.getSearch() == null||req.getSearch().size()==0) {
orders = (List<Order>) orderRepository.findAll();
} else {
Page<Order> page = orderRepository.listWithSearch(new PageRequest(
0,(int) orderRepository.count()), req
.getSearch());
orders = page.getContent();
}
if (productService.exportOrders(orders,response)) {
return null;
}
return null;
} |