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;
}