您的位置:首页 > 其它

浏览器下载服务器上的文件(EXCEL)

2017-04-06 08:53 411 查看
这是Excel类对Excel的部分操作

public HSSFWorkbook exportExcel(String title ,Map<String, String> headers, List<Map<String, Object>> dataBase) {

sheet = workbook.getSheetAt(0); // 默认的 第0个工作簿

int i = 0;
Map<String, Integer> cellAt = new HashMap<>();
row = sheet.createRow(0);

for (Map.Entry<String, String> map : headers.entrySet()) {
String key = map.getKey();
cell = row.createCell(i);
cell.setCellValue(map.getValue());
cellAt.put(key, i);
i++;
}
for (int j = 0; j < dataBase.size(); j++) {
row = sheet.createRow(j + 1);
for (Map.Entry<String, Integer> mapd : cellAt.entrySet()) {
Integer value = mapd.getValue();
String key = mapd.getKey();
cell = row.createCell(value);

Map<String, Object> dataBadeMap = dataBase.get(j);
Object dataBadeMapValue = dataBadeMap.get(key);
String dataBadeMapValueToString = dataBadeMapValue != null ? dataBadeMapValue.toString() : "";

cell.setCellValue(dataBadeMapValueToString);
}
}

HttpServletResponse response = Noxa.instance.getNoxaDispatcher().getResponse();
try(OutputStream out = response.getOutputStream();){
response.reset();
response.setContentType("application/x-download");//告诉浏览器你要下载东西才能弹出下载框让你选择下载路径
response.addHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(title+".xls", "UTF-8"));
workbook.write(out);
if(log.isInfoEnabled()){
log.info("导出成功");
}
out.flush();
} catch (Exception e) {
log.error("导出失败");
}

return workbook;
}

----------这一块是下载到服务器本地的

/*try {
FileOutputStream os = new FileOutputStream("D://upload//"+title+".xls");
workbook.write(os);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return workbook;
}
*/

----------


这里有个问题就是你通过Ajax来请求浏览器是不理你的,但是后台数据是有的,也照样有返回。但是浏览器就是不理你,我也不知道问题在哪,希望哪个大神可以指点一下。不过在界面上我们可以通过a标签的href属性来请求,或者通过form表单来提交。

第一次写。多指教
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  excel 服务器 浏览器
相关文章推荐