poi 生成excel

// 使用poi 2.5 创建excel文件
private void getExcelFile(Dto dto, HttpServletRequest req) {
Vs vs = new VsImpl();
List list = vs.getCorpPerosn(dto); // 从数据库中插入数据 返回动态bean DynaBean 的集合
if (list == null || list.size() == 0) {
return;
}
// 第一步,创建一个webbook,对应一个Excel文件
HSSFWorkbook wb = new HSSFWorkbook();
// 第二步,在webbook中添加一个sheet,对应Excel文件中的sheet
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "制卡信息", HSSFWorkbook.ENCODING_UTF_16);// 给工作薄添加名称
// 第三步,在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
HSSFRow row = sheet.createRow((int) 0);
// 第四步,创建单元格,并设置值表头 设置表头居中
HSSFCellStyle style = wb.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 创建一个居中格式
HSSFCell cell = null;

// 将需要添加进excel的数据放进集合LinkedHashMap 中
// LinkedHashMap 是有序的map集合
LinkedHashMap lhm = new LinkedHashMap();
lhm.put("x", "ac"); // x 是excel的列名, ac是数据库中的列名

String as[] = new String[lhm.size()];
lhm.keySet().toArray(as);

// 插入excel列名
for (int i = 0; i < as.length; i++) {
cell = row.createCell((short) i);
cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 设置中文转码格式
cell.setCellValue(new String(as[i].getBytes())); // 赋值
cell.setCellStyle(style); // 添加样式
}
// 将所有数据放入excel中
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(i + 1);
DynaBean db = (DynaBean) list.get(i);
for (int j = 0; j < as.length; j++) {
cell = row.createCell((short) j);
cell.setEncoding(HSSFCell.ENCODING_UTF_16); // 设置编码格式
cell.setCellValue(new String(db.get(lhm.get(as[j]).toString())
.toString().getBytes()));
cell.setCellStyle(style);
}
}
try {
FileOutputStream font = new FileOutputStream(dto.getAbsPath()
+ "/excel/" + dto.getAab069() + ".xls"); // 生成文件保存路径
wb.write(font);
font.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}

}

附带poi2.5 jar
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值