Java版Excel导出

<script type="text/javascript">//<![CDATA[
function toExcel() {
	window.open("XXXAction.do?method=toExcel&" + $('#bottomPageForm').serialize(),null,'width=400,height=300,top=100,left=100,toolbar=no,resizable=yes,scrollbars=yes'); 
}
//]]></script>

	public ActionForward toExcel(ActionMapping mapping, ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		DynaBean dynaBean = (DynaBean) form;
		super.encodeCharacterForGetMethod(dynaBean, request);
		Pager pager = (Pager) dynaBean.get("pager");
		pager.setPageSize(15);

		HttpSession session = request.getSession();
		UserInfo userInfo = (UserInfo) session.getAttribute(Constants.USER_INFO);


		List<MachineOnline> entityList = getFacade().getMachineOnlineService().getMachineOnlinePerDayPaginatedList(
				entity);

		WritableWorkbook wwb = null;
		String relativeFileName = "files/MachineOnline" + DateFormatUtils.format(new Date(), "yyyyMMddHHmmss")
				+ userInfo.getId() + ".xls";
		try {
			// 获取系统实际路径
			String SystemPath = getServlet().getServletContext().getRealPath(String.valueOf(File.separatorChar));

			// 首先要使用Workbook类的工厂方法创建一个可写入的工作薄(Workbook)对象
			wwb = Workbook.createWorkbook(new File(SystemPath + relativeFileName));
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (wwb != null) {
			// 创建一个可写入的工作表
			// Workbook的createSheet方法有两个参数,第一个是工作表的名称,第二个是工作表在工作薄中的位置
			WritableSheet ws = wwb.createSheet("sheet1", 0);

			ws.addCell(new Label(0, 0, "终端机编号"));
			ws.addCell(new Label(1, 0, "终端机名"));
			ws.addCell(new Label(2, 0, "在线日期"));

			Iterator<MachineOnline> it = entityList.iterator();
			int i = 1;
			while (it.hasNext()) {
				MachineOnline t = (MachineOnline) it.next();
				Label label0 = new Label(0, i, t.getMachine_no().toString());

				Label label1 = new Label(1, i, t.getMap().get("machine_name").toString());
				String dateTime = DateFormatUtils.format(t.getUpdate_time(), "yyyy-MM-dd");
				Label label2 = new Label(2, i, dateTime);

				try {
					// 将生成的单元格添加到工作表中
					ws.addCell(label0);
					ws.addCell(label1);
					ws.addCell(label2);
				} catch (RowsExceededException e) {
					e.printStackTrace();
				} catch (WriteException e) {
					e.printStackTrace();
				}
				i++;
			}

			try {
				// 从内存中写入文件中
				wwb.write();
				// 关闭资源,释放内存
				wwb.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (WriteException e) {
				e.printStackTrace();
			}
		}
		String ctx = super.getCtxPath(request);
		super.renderJavaScript(response, "window.location.href='" + ctx + "/" + relativeFileName + ";'");
		return null;
	}

你可能感兴趣的:(JavaScript,java,工作,Excel)