zoukankan      html  css  js  c++  java
  • POI 导出 Excel

    1.调用 Action 类中的 exproExcel 方法

    public String exproExcel() throws Exception {
    // 第一步,创建一个webbook,对应一个Excel文件
    HSSFWorkbook wb = new HSSFWorkbook();
    // 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
    HSSFSheet sheet = wb.createSheet("学生信息表");
    // 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
    HSSFRow row = sheet.createRow(0);
    // 第四步,创建单元格,并设置值表头 设置表头居中
    HSSFCellStyle style = wb.createCellStyle();
    style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式

    HSSFCell cell = row.createCell(0);
    cell.setCellValue("序号");
    cell.setCellStyle(style); //设置单元格居中

    cell = row.createCell(1);
    cell.setCellValue("用户名");
    cell.setCellStyle(style); //设置单元格居中

    cell = row.createCell(2);
    cell.setCellValue("密码");
    cell.setCellStyle(style); //设置单元格居中

    cell = row.createCell(3);
    cell.setCellValue("地址");
    cell.setCellStyle(style); //设置单元格居中

    // 第五步,写入实体数据 实际应用中这些数据从数据库得到,
                          // 得到数据保存在list中
    List<User> list = userService.selectUser();

    for (int i = 0; i < list.size(); i++){

    row = sheet.createRow((int) i + 1);
    User user = (User) list.get(i);

    sheet.autoSizeColumn(0); //根据内容自动调整单元格宽度 第一列
    sheet.autoSizeColumn(1); //根据内容自动调整单元格宽度 第二列
    sheet.autoSizeColumn(2); //根据内容自动调整单元格宽度 第三列
    sheet.autoSizeColumn(3); //根据内容自动调整单元格宽度 第三列

    // 第四步,创建单元格,并设置值
    cell = row.createCell(0); //创建单元格
    cell.setCellStyle(style); //设置单元格居中
    cell.setCellValue(i+1); //将值放在单元格中

    cell =row.createCell(1); //创建单元格
    cell.setCellStyle(style); //设置单元格居中
    cell.setCellValue(user.getName()); //将值放在单元格中

    cell =row.createCell(2);//创建单元格
    cell.setCellStyle(style); //设置单元格居中
    cell.setCellValue(user.getPassword());//将值放在单元格中
    }
    // 第六步,将文件存到指定位置
    try
    {
    FileOutputStream fout = new FileOutputStream("E:/user.xls");
    wb.write(fout);
    fout.close();
    System.out.println("导出成功");
    }
    catch (Exception e)
    {
    e.printStackTrace();
    System.out.println("导出失败");
    }
    return SUCCESS;
    }

  • 相关阅读:
    推荐前端开发使用的服务器环境开源项目 D2Server 可替代Apache
    JavaScript正则表达式的坑很深
    NodeJS + Sequelize + Mysql + Vue + Bootstrap
    wampserver使用过程中遇到的问题及相关配置
    生成解决方案时,无法导入以下密钥文件
    使用Image.GetThumbnailImage 方法返回缩略图
    C#操作xml文件进行增、删、改
    MessageBox.Show()时MessageBoxIcon的显示
    通过反射获取对象属性、属性的值,设置对象属性的值
    常用文档处理技巧
  • 原文地址:https://www.cnblogs.com/zhanggaosong/p/2984913.html
Copyright © 2011-2022 走看看