微科社区,轻松开发从此开始! 请登陆 免费注册

微科社区

当前位置:首页 > Java平台 > Servlet/JSP >

使用java生成excel功能实现

时间:2017-01-23 03:31  浏览:努力统计中...
1.jsp页面 发送请求地址:s9p67_createExcel.do public String createExcel() { try { HttpServletResponse response = ServletActionContext.getResponse(); OutputStream os = response.getOutputStream(); response.reset(); response.setContent

1.jsp页面
发送请求地址:s9p67_createExcel.do

public String createExcel() {
  try {
   HttpServletResponse response = ServletActionContext.getResponse();
   OutputStream os = response.getOutputStream();
   response.reset();
   response.setContentType("application/msexcel;charset=gbk");  //设置响应格式

//设置响应头,即报表头
   response.setHeader("Content-disposition", "attachment;filename=" + new String("业务受理量统计报表".getBytes(), "iso-8859-1") + ".xls");

   HSSFWorkbook hwb = new HSSFWorkbook();
   HSSFSheet sheet = hwb.createSheet("new Sheet");
   hwb.setSheetName(0, "业务受理量统计");

   HSSFRow row = sheet.createRow((short) 0);
   sheet.createFreezePane(0, 1);//设置第一行显示内容
   createCell(hwb, row, (short) 0, "业务类型");
   createCell(hwb, row, (short) 1, "操作名称");
   createCell(hwb, row, (short) 2, "数量");
   createCell(hwb, row, (short) 3, "收取金额");
   createCell(hwb, row, (short) 4, "工号");

//busBeans列表,为要显示的数据

for (int i = 1; i <= busBeans.size(); i++) {
    HSSFRow row1 = sheet.createRow((short) i);
    for (int j = 0; j < 5; j++) {
     if (j == 0) {
      createCell(hwb, row1, (short) j, busBeans.get(i - 1).getStatName());
     } else if (j == 1) {
      createCell(hwb, row1, (short) j, busBeans.get(i - 1).getFunName());
     } else if (j == 2) {
      createCell(hwb, row1, (short) j, busBeans.get(i - 1).getCountNum());
     } else if (j == 3) {
      createCell(hwb, row1, (short) j, busBeans.get(i - 1).getMoney());
     } else if (j == 4) {
      createCell(hwb, row1, (short) j, busBeans.get(i - 1).getLoginNo());
     }
    }
   hwb.write(os);
   os.close();
   return "createSuccess";
  } catch (Throwable e) {
   e.printStackTrace();
   this.forwardError(e.getMessage());
  }
  return "fail";
 }

 public void createCell(HSSFWorkbook wb, HSSFRow row, short col, String val) {
  HSSFCell cell = row.createCell(col);
  cell.setCellValue(val);
  HSSFCellStyle cellStyle = wb.createCellStyle();
  cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER_SELECTION);
  cell.setCellStyle(cellStyle);
 }

3.效果如图所示


    顶一下
    (0)
    0%
    踩一下
    (0)
    0%
    ------分隔线------
    栏目列表
    推荐内容