//标题
String [] columnNames= {"界别","班级名称","学号","姓名","出生日期","性别","电话","入学日期"};
//字段名
String [] columns= {"jname","cname","xid","name","birthday","sex","tel","starttime"};
//获取要导出的集合
List<User> list= userService.userList(null);
//调用导出方法 并给一个响应对象response
ExcelUtils.exportExcel(response, list, columnNames, columns, "测试", "班级信息");
exportExcel方法中的代码:
public static void exportExcel(HttpServletResponse response,List list, String[] columnNames, String[] columns,String sheetName, String filename) {
OutputStream fos = null;
try {
//响应输出流,让用户自己选择保存路径
fos = getOutputStream(response, filename);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet(sheetName);
HSSFCellStyle style = wb.createCellStyle(); // 样式对象
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 垂直
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 水平
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < columnNames.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(columnNames[i]);
cell.setCellStyle(style);
}
for (int i = 0; i < list.size(); i++) {
HSSFRow listRow = sheet.createRow(i + 1);
Object o = list.get(i);
for (int j = 0; j < columns.length; j++) {
HSSFCell listCell = listRow.createCell(j);
Method m = o.getClass().getMethod("get" + upperStr(columns[j]));
Object value = m.invoke(o);
if (value != null) {
listCell.setCellValue(value + "");
listCell.setCellStyle(style);
} else {
listCell.setCellValue("");
listCell.setCellStyle(style);
}
sheet.autoSizeColumn(j+1, true);//自适应,从1开始
}
}
wb.write(fos);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
pio导出
最新推荐文章于 2023-10-23 16:42:28 发布