java实现数据导出到Excel(全部导出)
直接代码:
public Result downLoad(Manager manager, HttpServletResponse response) throws IOException {
Result result = new Result();
//创建工作对象
HSSFWorkbook workbook = new HSSFWorkbook();
//创建的工作页对象
HSSFSheet sheet = workbook.createSheet("用户名单");
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFCreationHelper creationHelper = workbook.getCreationHelper();
cellStyle.setDataFormat(creationHelper.createDataFormat().getFormat("yyyy-MM-dd"));
List<Manager> list= managerService.findAll();
//创建行对象
HSSFRow row = sheet.createRow(0);
String []title={"用户名","创建时间","名字"};
for (int i = 0; i < title.length; i++) {
HSSFCell cell = row.createCell(i);
cell.setCellValue(title[i]);
}
for (int i = 1; i < list.size(); i++) {
row = sheet.createRow(i);
manager = list.get(i - 1);
row.createCell(0).setCellValue(manager.getId());
row.createCell(1).setCellValue(manager.getName());
row.createCell(2).setCellValue(manager.getPassword());
}
//创建Excel文件
response.setHeader("content-disposition", "attachment;filename=user.xls");
response.setContentType("application/vnd.ms-excel");
workbook.write(response.getOutputStream());
result.setMessage("导出成功");
return result;
}
其实类似这样的功能,好多的公司是封装成工具类直接可以调用的,这种的下载是直接在页面底部出现,也可以自己设置保存路径,也可以进行自定义导出。
自定义上导出:
@RequestMapping("/customExport")
public void customExport(String titles, String columns, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, IOException {
// 根据字段列表查询用户集合
List<User> users = userService.findAllColums(columns);
Workbook workbook = new HSSFWorkbook();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setDataFormat(workbook.getCreationHelper().createDataFormat().getFormat("yyyy-MM-dd"));
Sheet sheet = workbook.createSheet("用户信息");
Row row = sheet.createRow(0);
// 将用户信息导出到Excel表格中
// Excel=标题行+数据行
String[] title = titles.split(",");
for (int i = 0; i < title.length; i++) {
Cell cell = row.createCell(i);
cell.setCellValue(title[i]);
}
// [id,name,age,birthday]
// get+Cname = get方法名
String[] column = columns.split(",");
// 数据行
for (int i = 1; i <= users.size(); i++) {
row = sheet.createRow(i);
User user = users.get(i - 1);
Class<? extends User> c = user.getClass();
for (int j = 0; j < column.length; j++) {
Cell cell = row.createCell(j);
// id ---> Id
String cName = column[j];
String getMethodName = "get" + cName.substring(0, 1).toUpperCase() + cName.substring(1, cName.length());
Method method = c.getMethod(getMethodName, null);
// get方法对应的返回值
Object obj = method.invoke(user, null);
if (obj == null) {
continue;
}
if (obj instanceof Date) {
cell.setCellStyle(cellStyle);
cell.setCellValue((Date) obj);
} else {
cell.setCellValue(obj.toString());
}
}
}
response.setHeader("content-disposition", "attachment;filename=user.xls");
response.setContentType("application/vnd.ms-excel");
((HSSFWorkbook) workbook).write(response.getOutputStream());
}