Spring MVC 导出EXCEL
poi需要的jar包
核心导出工具类
主要是通过反射获取相应的字段,并从model中获取传入的数据,对应的插入表格中class 对象需要在调用的时候传入数据需要在调用前放入数据模型中表头信息需要自己传入
public class ExcelView <T>
extends AbstractXlsView{
private String modelName;
//数据模型名
private String fileName;
//文件名
private String []headNames;
//表头名数组
private Class<T>
clas;
public ExcelView(String modelName, String fileName, String[] headNames, Class<T>
clas) {
super();
this.modelName =
modelName;
this.fileName =
fileName;
this.headNames =
headNames;
this.clas =
clas;
}
//model : 数据模型
//workbook:一个Excel对象
@Override
protected void buildExcelDocument(Map<String, Object>
model,
Workbook workbook, HttpServletRequest request,
HttpServletResponse response) throws Exception {
//获得数据
List<T> datas = (List<T>
) model.get(modelName);
//构件Excel
//文件名
response.setHeader(
"Content-disposition"
,
"attachement;fileName="+URLEncoder.encode(fileName,"utf-8"
));
//基于Excel对象创建 Sheet 并命名
Sheet sheet = workbook.createSheet(clas.getSimpleName()+"表"
);
//通过反射获取 实体类的属性列表
Field []fields =
clas.getDeclaredFields();
for (
int i = -1 ; i < datas.size() ; i++
) {
//i从 -1 开始 ,-1时代表要插入的是表头信息(只是为了多循环一次,便于把表头加进去)
if ( i == -1
) {
Row row = sheet.createRow(0);
//创建表头的行
//取出表头字符串数组 并插入到excel的第一行
for (
int n = 0 ; n < headNames.length ; n++
) {
row.createCell(n).setCellValue( headNames[n] );
}
continue;
}
//数据体部分
Row row = sheet.createRow(i+1);
//创建行
T t = datas.get(i);
//获取数据第i个对象(数据对象是从0开始)
int k = 0
;
//将当前数据对象的数据放入对应行中
for (
int j = 0 ; j < fields.length ; j++ ,k++
) {
Field field = fields[j];
//获取
field.setAccessible(
true);
//授予权限
//处理不导出的字段
if ( field.getAnnotation(NoExport.
class) !=
null ) {
k--
;
continue;
}
//处理空字段
if ( field.get(t) !=
null && !""
.equals(field.get(t)) ) {
if ( field.getType() == Date.
class ) {
//日期转String
Cell cell =
row.createCell(k);
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue( new SimpleDateFormat("yyyy-MM-dd"
).format(field.get(t)) );
}else if ( field.getType() == Integer.
class ) {
row.createCell(k).setCellValue(String.valueOf(field.get(t)) );
}else {
row.createCell(k).setCellValue( (String) field.get(t) );
}
}
}
}
}
}
Controller 层
在这里传入 Student 的 class对象,并将数据防暑数据模型中, 传入表的字段数组
@Controller
public class Excel {
@RequestMapping("/getStudentsExcel"
)
public ModelAndView getStudentsTOExcel(ModelAndView mv) {
//假装 从数据库获取到数据
List<User> list =
new ArrayList<>
();
list.add( new User("张三", "121",
new Date(), "123@qq.com"
) );
list.add( new User("李四", "122",
new Date(), "223@qq.com"
) );
list.add( new User("王五", "123",
new Date(), "323@qq.com"
) );
list.add( new User("赵六", "124",
new Date(), "423@qq.com"
) );
list.add( new User("狗七", "125",
new Date(), "523@qq.com"
) );
//设置数据模型
mv.addObject("stus"
,list);
//设置非逻辑视图
String []headNames = {"姓名","密码","生日","邮箱"
};
mv.setView( new ExcelView<User>( "stus", "学生信息表.xls", headNames, User.
class ) );
return mv;
}
}
页面
简单的调用一下
<a href="getstudents">获取学生Excel
</a>
点击后的效果
导出文件效果
转载于:https://www.cnblogs.com/huangjianlong/p/7861444.html
相关资源:数据结构—成绩单生成器