源码:http://pan.baidu.com/s/1pLsiXZ1
pom.xml添加依赖:
@RequestMapping("/poi")
public voiddownstudents(HttpServletRequest request,HttpServletResponse response)throwsIOException {
List userModels =demoservice.getAll();
String[] headers = {"ID","姓名","年龄","密码","邮箱"};//导出的Excel头部,这个要根据自己项目改一下
// 声明一个工作薄
HSSFWorkbook workbook =newHSSFWorkbook();
// 生成一个表格
HSSFSheet sheet = workbook.createSheet();
// 设置表格默认列宽度为15个字节
sheet.setDefaultColumnWidth((short)18);
HSSFRow row = sheet.createRow(0);
for(shorti =0;i < headers.length;i++) {
HSSFCell cell = row.createCell(i);
HSSFRichTextString text =newHSSFRichTextString(headers[i]);
cell.setCellValue(text);
}
//遍历集合数据,产生数据行
Iterator user = userModels.iterator();
intindex =0;
while(user.hasNext()) {
index++;
row = sheet.createRow(index);
UserModel t = (UserModel) user.next();
//利用反射,根据javabean属性的先后顺序,动态调用getXxx()方法得到属性值
Field[] fields = t.getClass().getDeclaredFields();
for(shorti =0;i < fields.length;i++) {
HSSFCell cell = row.createCell(i);
Field field = fields[i];
String fieldName = field.getName();
String getMethodName ="get"
+ fieldName.substring(0,1).toUpperCase()
+ fieldName.substring(1);
try{
Class tCls = t.getClass();
Method getMethod = tCls.getMethod(getMethodName,
newClass[]{});
Object value = getMethod.invoke(t, newObject[]{});
String textValue =null;
if(valueinstanceofDate) {
Date date = (Date) value;
SimpleDateFormat sdf =newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");
textValue = sdf.format(date);
}else{
//其它数据类型都当作字符串简单处理
textValue = value.toString();
}
HSSFRichTextString richString =newHSSFRichTextString(textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);//定义Excel数据颜色
richString.applyFont(font3);
cell.setCellValue(richString);
}catch(SecurityException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(NoSuchMethodException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalArgumentException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(IllegalAccessException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}catch(InvocationTargetException e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition","attachment;filename=createList.xls");//默认Excel名称
response.flushBuffer();
workbook.write(response.getOutputStream());
}
上面复制还是会存在一个小bug,如果你的数据库数据为空就会报错,报错具体位置(如图):
这里要加一个简单判断就好啦: