进阶之路005 增删改查/数据导入导出之导出功能
1,在pom.xml中注意添加poi依赖
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.1</version>
</dependency>
2,//Controller层
/**
* 导出
*/
@RequestMapping("/heroDownLoad")
public R heroDownLoad(HttpServletResponse response ,@RequestParam Map<String, Object> params){
sysHeroService.downLoadList(response);
return R.ok();
}
3,//Service接口
//导出
void downLoadList(HttpServletResponse response);
4,//接口实现类
//导出表单
@Override
public void downLoadList(HttpServletResponse response) {
try {
String title="XXX表信息.xlsx";
XSSFWorkbook workbook = new XSSFWorkbook();
response.setCharacterEncoding("utf-8");
//以下设置格式
response.setHeader("conent-type", "application/octet-stream");
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("charset", "utf-8");
response.setHeader("content-disposition","attachment;filename="+new String(title.getBytes("gbk"), "ISO8859-1"));
/*--------------------------------------------------------------------------------*/
OutputStream os = response.getOutputStream();
XSSFSheet sheet=workbook.createSheet("text");
//创建第一行标题行
XSSFRow row=sheet.createRow(0);//创建标题行
XSSFCell id=row.createCell(0);
id.setCellValue("属性");
XSSFCell enHeroName=row.createCell(1);
enHeroName.setCellValue("属性1");
XSSFCell heroName=row.createCell(2);
heroName.setCellValue("属性2");
XSSFCell title01=row.createCell(3);
title01.setCellValue("属性3");
/*----------------------------------------------------------------------------------*/
//开始获取需要导入到excel中的数据
List<SysXxxEntity> list=sysXxxDao.getXxx(null,null,null,null);
int dataIndex=1;//取行索引
for(SysXxxEntity sysXxxEntity:list)
{
XSSFRow datarow=sheet.createRow(dataIndex);//创建数据的第一行
XSSFCell 属性Date=datarow.createCell(0);
属性.setCellValue(sysXxxEntity.get属性());
XSSFCell 属性1Date=datarow.createCell(1);
属性1.setCellValue(sysXxxEntity.get属性1());
XSSFCell 属性2Date=datarow.createCell(2);
属性2.setCellValue(sysXxxEntity.get属性2());
XSSFCell 属性3Date=datarow.createCell(3);
属性3.setCellValue(sysXxxEntity.get属性3());
dataIndex++;
}
workbook.write(os);
os.flush();
os.close();
workbook.close();
}
catch (Exception e) {
System.out.println(e);
}
}