java集成excel报表_java-运用Spring实现Excel报表

如果想使用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中配置视图解析器:

已标记关键词 清除标记
表情包
插入表情
评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页