POI实现excel导出功能
程序员文章站
2024-03-21 08:45:52
...
/**
* Export工具类
*/
public void exportUtil (){
//list为查询出的数据集合
List list = new ArrayList();
//导出excel文件的名字
String filename = "文件名字";
// /**
// * 获取response对象 获取HttpServletResponse response ;
// */
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("gbk"), "iso8859-1")+".xls");
//创建Excel
HSSFWorkbook wb = new HSSFWorkbook();
//创建第一个sheet取名sheet0
HSSFSheet sheet = wb.createSheet("sheet0");
//表头名称
String titles = "姓名,电话,QQ,邮箱,留言内容";
//对应的数据库字段 (查询出的list)
String fields = "name,phone,qq,email,content";
ExportUtil.outputHeaders(titles.split(","), sheet);
ExportUtil.outputColumns(fields.split(","), list, sheet, 1);
//获取输出流,写入excel 并关闭
ServletOutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
}
/**
* 设置sheet表头信息
* @param titlesInfo 表头的String数组
* @param sheet
*/
public static void outputHeaders(String[] titlesInfo,HSSFSheet sheet ){
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < titlesInfo.length; i++) {
sheet.setColumnWidth(i, 4000);
row.createCell(i).setCellValue(titlesInfo[i]);
}
}
/**
* 循环插入数据
* @param headersInfo 表体的String数组
* @param columnsInfo 包含表体数据的list集合
* @param sheet
* @param rowIndex 从第几行开始插入数据
*/
public static void outputColumns(String[] headersInfo,List columnsInfo,HSSFSheet sheet,int rowIndex ){
HSSFRow row ;
//循环插入多少行
for (int i = 0; i < columnsInfo.size(); i++) {
row = sheet.createRow(rowIndex+i);
Object obj = columnsInfo.get(i);
//循环每行多少列
for (int j = 0; j < headersInfo.length; j++) {
Object value = getFieldValueByName(headersInfo[j],obj);
if(value == null){
value="";
}
row.createCell(j).setCellValue(value.toString());
}
}
}
/**
* 根据对象的属性获取值
* @param string
* @param obj
* @return
*/
private static Object getFieldValueByName(String fieldName, Object obj) {
String firstLetter = fieldName.substring(0,1).toUpperCase();
String getter = "get" +firstLetter + fieldName.substring(1);
try {
Method method = obj.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(obj, new Object[]{});
return value;
} catch (Exception e) {
e.printStackTrace();
logger.error("属性不存在!");
return null;
}
}