概述
如果想使用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
Object> model,
HSSFWorkbook workbook,
HttpServletRequest request, HttpServletResponse
reponse)
throws Exception {
reponse.setHeader("Content-
Disposition", "inline;filename="+new String("用户列
表".getBytes(),"iso-8859-1"));
List userList =(List)
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 userList = new ArrayList();
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中配置视图解析器:
最后
以上就是慈祥猫咪为你收集整理的java集成excel报表_java-运用Spring实现Excel报表的全部内容,希望文章能够帮你解决java集成excel报表_java-运用Spring实现Excel报表所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复