第一步:MAVEN: pom.xml
org.apache.poi
poi-ooxml
3.14
第二步:SERVER: FileBPO
void exportExcelCellRangeAddress(HttpServletRequest req, HttpServletResponse res,String fileName, String sheetName, List title,
List
解释:fileName为文件名,sheetName为excel工作溥名,title为excel表头名称放在第一行,values为对象一般是对象转为map类型,keys为对象中的属性,column为要合并的哪一列。
第三步:SERVERIMPL实现类: FileBPOIMPL
@Override
public void exportExcelCellRangeAddress(HttpServletRequest req, HttpServletResponse res,String fileName, String sheetName,
List title, List
}
//创建Excel文件(仅有一个sheet)
public static HSSFWorkbook createExcelCellRangeAddress(String sheetName,List title,List
第四步:调用
@Autowired
private FileBPO fileBPO;
@RequestMapping(value = "/doExportExcelAll")
@ResponseBody
public void doExportExcelAll(HttpServletRequest req, HttpServletResponse res) throws Exception{
//查看获取list
List userList=dao.select();//这里查库的结果,在这里我就不写了,如果不懂得可以留言
String fileName = "测试.xls";
String sheetName = "测试";
List title = new ArrayList();//标题列表
title.add("用户名");title.add("密码");
List keys = new ArrayList();//Map获取值的key
keys.add("username");keys.add("password");
List
//合并第1列和第2列,也可以不合并,不设置就是不合并
column.add(1);
column.add(2);
fileBPO.exportExcelCellRangeAddress(req, res,fileName,sheetName, title, values, keys,column);
}
//对象转map方法,利用反射
public static Map objectToMap(Object obj) {
Map map = new HashMap<>();
Class> clazz = obj.getClass();
try {
for (Field field : clazz.getDeclaredFields()) {
field.setAccessible(true);//设置可以访问私有变量
String fieldName = field.getName();
Object value = null;
if(field.get(obj) != null) {
value = field.get(obj);
}
map.put(fieldName, value);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return map;
}