java execl生成并下载,需要下载到当前浏览器的默认下载目录

半颗糖1 2016-03-02 10:03:39
public boolean exportExcel(HttpServletRequest request,HttpServletResponse response, List list,
String couponCount, String couponId) throws IOException{
Workbook wb = new XSSFWorkbook();
String filename = couponCount + "_" + couponCount + "_" + RandomStringUtils.randomAlphanumeric(2);// 随即生成长度为2包含字母和数字的字符串
filename = filename + ".xlsx";
Sheet sheet = (Sheet) wb.createSheet();

for (int i = 0; i < list.size(); i++) {
String order = (String) list.get(i);
Row row = sheet.createRow(0);
// 循环写入列数据
row.createCell(i).setCellValue(order);

}

response.setContentType("multipart/form-data");
response.setHeader("Content-disposition", "attachment;filename=" + filename);

try {

FileOutputStream fileOutputStream = new FileOutputStream(filename);
wb.write(fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();

return true;
} catch (Exception e) {
System.out.println("It cause Error on WRITTING excel workbook: ");
e.printStackTrace();
}

return false;
}

代码如上,下载后的目录为eclipse的安装目录,有谁可以帮我改成浏览器的下载目录么
...全文
614 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
钢铁雄心 2016-03-02
  • 打赏
  • 举报
回复
1、生成Excel 在 /data/tools/apache-tomcat-8080/webapps/XXX/upload/目录下 // 下载 String fileName = "文件名.xls"; response.reset();// 不加这一句的话会出现下载错误 response.setHeader("Content-disposition", "attachment; filename=" + fileName);// 设定输出文件头 response.setContentType("text/x-plain");// 定义输出类型 try { ServletOutputStream out = response.getOutputStream(); String path = "/data/tools/apache-tomcat-8080/webapps/XXX/upload/" + fileName; //Excel在服务器上的路径 File file = new File(path); FileInputStream fis = new java.io.FileInputStream(file); ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream(4096); byte[] cache = new byte[4096]; for (int offset = fis.read(cache); offset != -1; offset = fis.read(cache)) { byteOutputStream.write(cache, 0, offset); } byte[] bt = null; bt = byteOutputStream.toByteArray(); out.write(bt); out.flush(); out.close(); fis.close(); if (file.exists()) { file.delete(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } 效果就是Excel 通过浏览器下载

50,549

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧