导出数据表中数据为Excel文件(Java版)

fuyun 2009-09-17
代码如下:
<%@page language="java" contentType="text/html; charset=utf-8"%>
<%@page import="java.util.List"%>
<%@page import="com.fuyun.hp.common.PubUtil"%>
<%@page import="com.fuyun.hp.hibernate.mapping.RadioType"%>
<%@page import="com.fuyun.hp.hibernate.mapping.RadioTypeDAO"%>
<%
  //出于考虑显示格式,实际运行时,请将代码中的全角空格转换为半角空格   
  //代码中的PubUtil.nvl(Object)方法,当Object为null时返回空串(也就是类似Oracle中的nvl方法)
  //建议不采用saveAs方式
  request.setCharacterEncoding("utf-8");
  String outputFileName = "radioTree.xls";
  String templateFile = getServletContext().getRealPath("/") + "formal/excel/radioTree.xls";
  String outputFile = getServletContext().getRealPath("/") + "formal/excel/" + outputFileName;
  String outputFileUrl = PubUtil.getSiteUrl(request) + "/formal/excel/" + outputFileName;
  com.fuyun.hp.excel.ExcelOperate eOper = new com.fuyun.hp.excel.ExcelOperate(templateFile);
  int row, cols;
  File file = new File(outputFile);
  RadioTypeDAO radioDao = RadioTypeDAO.getInstance();
  List<RadioType> rtList;
  String sheetName = "电台树";

  if (file.exists())
    file.delete();

  cols = 0;
  eOper.writeCell(sheetName, 1, ++cols, "id");
  eOper.writeCell(sheetName, 1, ++cols, "上级id");
  eOper.writeCell(sheetName, 1, ++cols, "名称");
  eOper.writeCell(sheetName, 1, ++cols, "排序");
  row = 2;

  rtList = radioDao.find("from RadioType order by parentId asc,orderIndex asc");
  for (RadioType rt : rtList){
    cols = 0;
    eOper.writeCell(sheetName, row, ++cols, rt.getId());
    eOper.writeCell(sheetName, row, ++cols, rt.getParentId());
    eOper.writeCell(sheetName, row, ++cols, rt.getName());
    eOper.writeCell(sheetName, row, ++cols, rt.getOrderIndex());
    row++;
  }
  eOper.saveAs(outputFile);

  response.reset();
  response.setContentType("application/force-download;");
  response.setHeader("Content-Disposition", "attachment; filename=" + outputFileName);
  response.sendRedirect(outputFileUrl);
%>
Global site tag (gtag.js) - Google Analytics