apache poi导出excel报表
/** * desp:导出excel表格* @param model
* @param req
* @param resp
* @return
* @throws Exception
*/
@RequestMapping("/exportExcel")
public String exportExcel(HttpServletRequest req, HttpServletResponse resp) {
//声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
//申明一个单子并命名
HSSFSheet sheet = wb.createSheet("个人收入表");
//给单元格一个默认的长度(原文字符个数)
sheet.setDefaultColumnWidth(10);
//生成样式
HSSFCellStyle style = wb.createCellStyle();
//样式字体居中
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
//创建表头,也就是表头
HSSFRow header = sheet.createRow(0);
//给表头创建单元格
HSSFCell cell = header.createCell(0);
cell.setCellValue("姓名");
cell.setCellStyle(style);
cell = header.createCell(1);
cell.setCellValue("股票收入(万)");
cell.setCellStyle(style);
cell = header.createCell(2);
cell.setCellValue("基金收入(万)");
cell.setCellStyle(style);
cell = header.createCell(3);
cell.setCellValue("工资收入(万)");
cell.setCellStyle(style);
cell = header.createCell(4);
cell.setCellValue("总收入(万)");
cell.setCellStyle(style);
//获取数据 TODO 应该从调用serivce得到数据,serivce再调用dao得到数据
List<Person> list = new ArrayList<Person>();
list.add(new Person(1, "林冲", 100, 50, 20));
list.add(new Person(2, "宋江", 80, 40, 10));
list.add(new Person(3, "卢俊义", 80, 40, 10));
//向单元格里填充数据
for(final Person person : list) {
HSSFRow row = sheet.createRow(person.getId());
row.createCell(0).setCellValue(person.getName());
row.createCell(1).setCellValue(person.getStockIncome());
row.createCell(2).setCellValue(person.getFoundationIncome());
row.createCell(3).setCellValue(person.getSalaryIncome());
row.createCell(4).setCellValue(
person.getFoundationIncome() + person.getStockIncome() + person.getSalaryIncome()
);
}
//写文件,将生成的表单写入服务器本地文件
FileOutputStream os = null;
try {
os = new FileOutputStream("E://个人收入表.xls");
wb.write(os);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if(os != null) {
os.close();
os = null;
}
} catch(IOException e) {
e.printStackTrace();
}
}
ReportExcel.download(filePath, resp);
return null;
}
页:
[1]