Servlet端下载txt和excel文件实例

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 {

		// 生成xls
		try {
			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 {

		// 生成txt
		try {
			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.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值