java生成-excel-并导出文件

7 篇文章 0 订阅
2 篇文章 0 订阅

==================controller============== 


    @RequestMapping("/RegisterExcel")
    public void expicinfo(HSSFWorkbook workbook,HttpSession session,HttpServletResponse response){
 	    String filename="信息.xls";
 	    List<Registration> logList=logService.getRegisterInfo();
 	   
 	    // 创建一个Excel文件  :HSSFWorkbook workbook
 	    // 创建一个Excel的Sheet  :HSSFSheet
	    HSSFSheet sheet=workbook.createSheet();     
			
	    // 设置列宽    
		sheet.setColumnWidth(0, 1000);    
		sheet.setColumnWidth(1, 3500);    
		sheet.setColumnWidth(2, 3500); 
		sheet.setColumnWidth(3, 5000); 
		    
		// 创建第一行    
		HSSFRow header=sheet.createRow(0);
		// 创建第一行   参数   
		header.createCell(0).setCellValue("序号");
		// 创建第二行参数   
		header.createCell(1).setCellValue("用户");
		header.createCell(2).setCellValue("操作");
		header.createCell(3).setCellValue("注册时间");
			
		for(int i=1;i<=logList.size();i++){
			HSSFRow row=sheet.createRow(i);
			Registration inv=logList.get(i-1);
			row.createCell(0).setCellValue(i);
			row.createCell(1).setCellValue(inv.getUser().getName());
			row.createCell(2).setCellValue("注册");
			//日期转换
			
			DateFormat formater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(formater.format(inv.getRestime()) !=null && formater.format(inv.getRestime()) !=""){
				String date= formater.format(inv.getRestime());
				row.createCell(3).setCellValue(date);
			}
		}
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try { 
		    workbook.write(os);
		    byte[] content = os.toByteArray();
		    InputStream is = new ByteArrayInputStream(content);
		    response.addHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes(),"ISO-8859-1"));
		    response.setContentType("application/vnd.ms-excel;charset=utf-8");
		    ServletOutputStream out = response.getOutputStream();
		    bis = new BufferedInputStream(is);
		    bos = new BufferedOutputStream(out);

		    byte[] buff = new byte[2048];
		    int bytesRead;

		    // Simple read/write loop.
		    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
		    	bos.write(buff, 0, bytesRead);
	        }
		} catch (UnsupportedEncodingException e) {
		    e.printStackTrace();
		} catch (IOException e) {
		    e.printStackTrace();
		}finally {
		    try {
		    	if (bis != null)
		    		{bis.close();}
		    	if (bos != null)
		    		{bos.close();}
		    } catch (IOException e) {
		    	e.printStackTrace();
		    }
		}
    }

 ===================html==========

<a href="<%=basePath%>log/RegisterExcel">导出</a>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值