您的位置:首页 > 编程语言 > Java开发

java实现下载功能Controller层代码

2017-12-17 15:17 369 查看
public class DownloadExcelController(HttpServletRequest request,HttpServletResponse response){
//创建HSSFWorkbook对象,对应一个EXCEL文件
HSSFWorkbook wb=new HSSFWorkbook();
//创建一个HSSFSheet,对应excel中的页
HSSFSheet sheet=wb.createSheet("学生列表");
//创建HSSFRow,对应excel中的行
HSSFRow row=sheet.createRow(0);
//创建HSSFCell,对应excel中的列
HSSFCell cell=sheet.createCell(0);
cell.setCellValue("ID");
cell=row.createCell(1);
cell.setCellValue("NAME");
cell=row.createCell(2);
cell.setCellValue("AGE");
//往excel中循环添加数据
for(int i=0;i<5;i++){
row=sheet.createRow(i+1);
cell=row.createCell(0);
cell.setCellValue(100+i);
cell=row.createCell(1);
cell.setCellValue("NAME"+i);
cell=row.createCell(2);
cell.setCellValue(20+i);
}

//把wb写入磁盘
//OutputStream os=new FileOutputStream("d:test.xls");
//设置响应类型
response.setContentType("application/octet;charset="UTF-8");
//获取用户浏览器信息
String browser=request.getHeader("User-Agent");

String filename=URLEncoder.encode("学生列表","UTF-8")

//火狐浏览器

if(browser.toLowerCase().contains("firefox")){
filename=new String("学生列表".getBytes("UTF-8"),"iso8859-1")

}



//设置浏览器的处理方式
response.addHeader("Content-Dispotion","attachment";filename="学生列表.xls")
OutputStream os=response.getOutputStream();
wb.write(os);
os.flush;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息