六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 32|回复: 0

Servlet端下载txt和excel文件实例

[复制链接]

升级  14.67%

18

主题

18

主题

18

主题

秀才

Rank: 2

积分
72
 楼主| 发表于 2013-1-28 19:16:57 | 显示全部楼层 |阅读模式
Servlet端下载txt和excel文件实例

1.下载excel文件:

import jxl.Workbook;import jxl.write.Label;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;public class ExcelDownload extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 生成xlstry {Date d = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_kkmmss ");String random = sdf.format(d);String targetFile = random + ".excel";response.setContentType("application/vnd.ms-excel");response.addHeader("Content-Disposition","attachment;   filename=\"" + targetFile + "\"");OutputStream os = response.getOutputStream();WritableWorkbook wwb = Workbook.createWorkbook(os);// 新建一张表WritableSheet wsheet = wwb.createSheet("record", 0);// 设置表头Label label = new Label(0, 0, "");wsheet.addCell(label);label = new Label(0, 0, "会员姓名");wsheet.addCell(label);label = new Label(1, 0, "卡号");wsheet.addCell(label);label = new Label(2, 0, "联系地址");wsheet.addCell(label);label = new Label(3, 0, "邮编");wsheet.addCell(label);label = new Label(4, 0, "联系电话");wsheet.addCell(label);label = new Label(5, 0, "手机");wsheet.addCell(label);label = new Label(6, 0, "Email");wsheet.addCell(label);label = new Label(7, 0, "性别");wsheet.addCell(label);wwb.write();wwb.close();os.close();response.flushBuffer();} catch (Exception e) {System.out.println("生成信息表(Excel格式)时出错:");e.printStackTrace();}}}
 2.生成txt文件:

import jxl.Workbook;import jxl.write.Label;import jxl.write.WritableSheet;import jxl.write.WritableWorkbook;public class TxtDownLoad extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// 生成txttry {Date d = new Date();SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_kkmmss ");String random = sdf.format(d);String targetFile = random + ".csv";response.setContentType("application/x-msdownload");response.addHeader("Content-Disposition","attachment;   filename=\"" + targetFile + "\"");OutputStream os = response.getOutputStream();String temp = "你好啊!";os.write(temp.getBytes());os.close();response.flushBuffer();} catch (Exception e) {System.out.println("生成txt文件时出错:");e.printStackTrace();}}}
 

 
注:这里生成excel时,用到了jxl包,是专门用于java对于Excel文件格式的API.
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表