struts2中使用poi导出excel数据

struts配置文件

<action name="export" class="com.bos.ExportAction">
	<result type="stream">
		<param name="contentType">${contentType}</param>
		<param name="contentDisposition">attachment;filename=${filename}</param>
		<param name="inputName">targetFile</param>
	</result>
</action>

java代码

</pre><pre>
public String getContentType() {
	return ServletActionContext.getServletContext().getMimeType(".xls");
}

public String getFilename() throws UnsupportedEncodingException {
	String filename = "分区数据.xls";
//	return new String(filename.getBytes("utf-8"),"ISO8859-1");
	return URLEncoder.encode(filename,"utf-8");
}

public InputStream getTargetFile() throws FileNotFoundException {
	return new FileInputStream(ServletActionContext.getServletContext().getRealPath("/export.xls"));
}

@SuppressWarnings("unchecked")
public String execute() throws Exception {
	//查询条件数据保存到session中,获取
	List<Subarea> subareas = (List<Subarea>) ServletActionContext.getRequest().getSession().getAttribute("subareas");

	// 第一步 创建文档对象 
	Workbook wb = new HSSFWorkbook();
	// 第二步 创建sheet
	Sheet sheet = wb.createSheet("分区信息");
	// 第三步 写数据
	// 标题
	Row headRow = sheet.createRow(0);
	String[] heads = { "省", "市", "区(县)", "定区编码", "关键字", "起始号", "结束号","单双号", "省市区编码" };
	for (int i = 0; i < heads.length; i++) {
		Cell cell = headRow.createCell(i);
		cell.setCellValue(heads[i]);
	}

	// 内容生成
	for (int i = 0; i < subareas.size(); i++) {
		// 从第二行开始
		Row row = sheet.createRow(i + 1);
		Subarea subarea = subareas.get(i);
		String decidedzoneid = subarea.getDecidedzone() == null ? ""
				: subarea.getDecidedzone().getId();
		Region region = subarea.getRegion();
		String[] contents = { region.getProvince(), region.getCity(),
				region.getDistrict(), decidedzoneid,
				subarea.getAddresskey(), subarea.getStartnum(),
				subarea.getEndnum(), subarea.getSingle(),
				subarea.getPosition() };
		for (int j = 0; j < contents.length; j++) {
			Cell cell = row.createCell(j);
			cell.setCellValue(contents[j]);
		}
	}
	wb.write(new FileOutputStream(ServletActionContext.getServletContext().getRealPath("/export.xls")));
	return SUCCESS;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值