如果想使用excel展示用户列表,仅需扩展Spring的AbstractExcelView 或AbstractJExcelView ,实现buildExcelDocument()方法,在方法中使用模型数据对象构造Excel文档
代码:
package com.accp.web;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.time.DateFormatUtils;
import
org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import
org.springframework.web.servlet.view.document.AbstractE
xcelView;
import com.accp.domain.User;
/**
* 显示用户列表Excel的视图类
* @author Administrator
*
*/
public class UserListExcelView extends
AbstractExcelView {
@SuppressWarnings("unchecked")
@Override
protected void buildExcelDocument(Map<String,
Object> model,
HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse
reponse)
throws Exception {
reponse.setHeader("Content-
Disposition", "inline;filename="+new String("用户列
表".getBytes(),"iso-8859-1"));
List<User> userList =(List<User>)
model.get("userList");
HSSFSheet sheet = workbook.createSheet
("users");
HSSFRow header = sheet.createRow(0);
header.createCell(0).setCellValue(new
HSSFRichTextString("姓名"));
header.createCell(1).setCellValue(new
HSSFRichTextString("积分"));
header.createCell(2).setCellValue(new
HSSFRichTextString("最后登录时间"));
int rowNum = 1;
for(User user: userList){
HSSFRow row = sheet.createRow
(rowNum++);
row.createCell(0).setCellValue
(new HSSFRichTextString(user.getUserName()));
row.createCell(1).setCellValue
(user.getCredit());
String createDate =
DateFormatUtils.format(user.getLastVisit(),"YYYY-MM-
dd");
row.createCell(2).setCellValue
(new HSSFRichTextString(createDate));
}
}
}
2.在前端控制器中添加一个相应的请求处理方法:
@Controller()
@RequestMapping("/user")
public class UserController {
@RequestMapping( "showUserListByXls")
public String showUserListInExcel(ModelMap mm) {
Calendar calendar = new GregorianCalendar();
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setUserName("tom");
user1.setCredit(20);
calendar.set(1980, 1, 1);
user1.setLastVisit((calendar.getTime()));
User user2 = new User();
user2.setUserName("john");
user2.setCredit(10);
user2.setLastVisit(calendar.getTime());
userList.add(user1);
userList.add(user2);
mm.addAttribute("userList", userList);
return "userListExcel";
}
}
}
3.在xxx-servlet-xml中配置视图解析器:
<bean class="org.springframework.web.servlet.view.BeanNameViewResolver" p:order="10"/>
<bean id="userListExcel" class="com.contorller.UserListExcelView">
</bean>