java从服务器下载xls文件到客户端

查考网上的代码写了一个下载xls文件到客户端的jsp页面,只要将服务器的文件地址传给这个jsp页面就可以实现下载文件到客户端了。

Code:
  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>  
  3. <%@ page import="java.io.*" %>  
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head>  
  7.         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  8.         <link href="styles/basic.css" rel="stylesheet" type="text/css" />  
  9.         <title>download</title>  
  10. </head>  
  11. <%      
  12.      response.setCharacterEncoding("gb2312");      
  13.      request.setCharacterEncoding("gb2312");      
  14.      
  15.     if (request.getParameter("file") != null) {      
  16.          OutputStream os = null;      
  17.          FileInputStream fis = null;      
  18.         try {      
  19.              String file = request.getParameter("file");      
  20.             if (!(new File(file)).exists()) {      
  21.                  System.out.println("没有文件");      
  22.                 return;      
  23.              }      
  24.              System.out.println("文件名为:"+file);      
  25.              os = response.getOutputStream();      
  26.              response.setHeader("content-disposition", "attachment;filename=" + file);      
  27.              response.setContentType("application/vnd.ms-excel");//此项内容随文件类型而异      
  28.             byte temp[] = new byte[1000];      
  29.              fis = new FileInputStream(file);      
  30.             int n = 0;      
  31.             while ((n = fis.read(temp)) != -1) {      
  32.                  os.write(temp, 0, n);      
  33.              }      
  34.          } catch (Exception e) {      
  35.              out.print("出错");      
  36.          } finally {      
  37.             if (os != null)      
  38.                  os.close();      
  39.             if (fis != null)      
  40.                  fis.close();      
  41.          }      
  42.          out.clear();      
  43.          out = pageContext.pushBody();      
  44.      
  45.      }      
  46. %>      
  47.      
  48. <form action="" method="post">      
  49.      <select name="file">      
  50.          <option value="D://test//test.xls">      
  51.              冷山sky_snow      
  52.          </option>      
  53.      </select>      
  54.      <input type="submit"/>      
  55. </form>   
  56. </html>  

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值