天天看點

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

繼續閱讀