您的位置:首页 > 其它

针对于项目中用到的技术点的归纳{导出excel}

2017-08-05 08:52 211 查看
这是我在项目所遇到的,导出Excel表格功能,为了以后工作的需要,所以我把项目所遇到的技术点以及功能模块记录下来,也是为了以后的工作中遇到同样的就不必费心思去写了,虽然不是很复杂但也得花点时间的,下面是代码

// 导出用户信息到excel表
public void downloadOrg_emp(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//创建excel表头部分
String[] execelHeader = {"用户账户","真实姓名","角色","操作"};

//从数据库中查询人员的信息
List<Org_employee> list = userService.getAllOrgEmp();
//创建excel对象
HSSFWorkbook wb = new HSSFWorkbook();
//创建sheet
HSSFSheet sheet = wb.createSheet();
// sheet.createFreezePane(1, 3);//冻结
//设置列宽
sheet.setColumnWidth(0, 3500);
sheet.setColumnWidth(1, 3500);
sheet.setColumnWidth(2, 3500);
sheet.setColumnWidth(3, 3500);

//创建行(第一行表头)
HSSFRow row = sheet.createRow((int)0);

//为表头创建样式
HSSFCellStyle style = wb.createCellStyle();

//设置字体 样式
HSSFFont headfont = wb.createFont();
//字体
headfont.setFontName("黑体");
//字体大小
headfont.setFontHeightInPoints((short)15);
//字体的粗细
headfont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//将设置好的样式添加到样式中
style.setFont(headfont);

//设置第一行表头信息
for(int i=0;i<execelHeader.length;i++){
//在一行中创建列
HSSFCell cell = row.createCell(i);
//设置列中的表头信息
cell.setCellValue(execelHeader[i]);
//为列设置样式
cell.setCellStyle(style);
}
//设置其余行的列的值
//创建样式
HSSFCellStyle styleOther = wb.createCellStyle();
//居中显示
styleOther.setAlignment(HSSFCellStyle.ALIGN_CENTER);

for(int i=0;i<list.size();i++){
row=sheet.createRow(i+1);
Org_employee orgEmp = list.get(i);
Integer rid = orgEmp.getRoleid();
//查询角色
OrgRole role = roleService.getROleByRid(rid);
//为每一行放值
HSSFCell cell1 = row.createCell(0);
cell1.setCellValue(orgEmp.getLoginname());
cell1.setCellStyle(styleOther);
HSSFCell cell2 = row.createCell(1);
cell2.setCellValue(orgEmp.getUsername());
cell2.setCellStyle(styleOther);
HSSFCell cell3 = row.createCell(2);
if(role.getOrg_id() == orgEmp.getId()){
cell3.setCellValue(role.getRoleName());
}
HSSFCell cell4 = row.createCell(3);
cell4.setCellValue("操作");
cell4.setCellStyle(styleOther);
}

//设置下载时的客户端Excel的名称
String filename = "未命名.xls";
filename = URLEncoder.encode(filename,"utf-8");
//设置响应信息类型
response.setContentType("application/vnd.ms-excel");
//设置响应的头信息
response.setHeader("Content-disposition", "attachment;filename="+filename);
//通过输出 流将文件输出到客户端
OutputStream outputStream = response.getOutputStream();
wb.write(outputStream);
outputStream.flush();
outputStream.close();
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: