版权声明:如有錯誤,請各位大神及時指出——陳達 https://blog.csdn.net/chen644168023/article/details/82833020
public void customExport(HttpServletRequest request,String titles, String columns, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException, IOException {
// 根据字段列表查询用户集合
List<User> users = userService.queryUesrByColumns(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());
}
}
}
String realPath = request.getSession().getServletContext().getRealPath("//userexl");
workbook.write(new FileOutputStream(realPath+"\\test5.xls"));
workbook.close();
FileInputStream fileInputStream = new FileInputStream(new File(realPath, "test5.xls"));
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename=" + new String("test5.xls".getBytes("utf-8"), "ISO8859-1"));
ServletOutputStream outputStream = response.getOutputStream();
byte[] b = new byte[2048];
int len;
while (true){
len = fileInputStream.read(b);
if(len==-1) break;;
outputStream.write(b,0,len);
}
outputStream.close();
fileInputStream.close();
}