源碼:http://pan.baidu.com/s/1pLsiXZ1
pom.xml添加依賴:

@RequestMapping("/poi")
public voiddownstudents(HttpServletRequest request,HttpServletResponse response)throwsIOException {
List userModels =demoservice.getAll();
String[] headers = {"ID","姓名","年齡","密碼","郵箱"};//導(dǎo)出的Excel頭部,這個(gè)要根據(jù)自己項(xiàng)目改一下
// 聲明一個(gè)工作薄
HSSFWorkbook workbook =newHSSFWorkbook();
// 生成一個(gè)表格
HSSFSheet sheet = workbook.createSheet();
// 設(shè)置表格默認(rèn)列寬度為15個(gè)字節(jié)
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);
}
//遍歷集合數(shù)據(jù),產(chǎn)生數(shù)據(jù)行
Iterator user = userModels.iterator();
intindex =0;
while(user.hasNext()) {
index++;
row = sheet.createRow(index);
UserModel t = (UserModel) user.next();
//利用反射,根據(jù)javabean屬性的先后順序,動(dòng)態(tài)調(diào)用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{
//其它數(shù)據(jù)類型都當(dāng)作字符串簡單處理
textValue = value.toString();
}
HSSFRichTextString richString =newHSSFRichTextString(textValue);
HSSFFont font3 = workbook.createFont();
font3.setColor(HSSFColor.BLUE.index);//定義Excel數(shù)據(jù)顏色
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");//默認(rèn)Excel名稱
response.flushBuffer();
workbook.write(response.getOutputStream());
}
上面復(fù)制還是會(huì)存在一個(gè)小bug,如果你的數(shù)據(jù)庫數(shù)據(jù)為空就會(huì)報(bào)錯(cuò),報(bào)錯(cuò)具體位置(如圖):

這里要加一個(gè)簡單判斷就好啦:
