引入maven配置
返回数据格式
生成excel模板
private HSSFWorkbook Excels(String tableName, List groupList, String[] headLists) {
//创建excel
HSSFWorkbook sheets =new HSSFWorkbook();
if (groupList.size() !=0) {
//创建一个工作表(表名)
HSSFSheet sheet = sheets.createSheet(tableName);
//设置样式
HSSFCellStyle cellStyle = sheets.createCellStyle();
cellStyle.setAlignment(HorizontalAlignment.LEFT);//设置单元格水平方向对齐方式 居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//设置单元格垂直方向对齐方式 居中
//设置字体样式
HSSFCellStyle cellStyle4 = sheets.createCellStyle();
HSSFFont font = sheets.createFont();//设置字体样式
font.setFontName("微软雅黑");
font.setFontHeightInPoints((short)12);//设置字号
cellStyle4.setFont(font);//字体风格放入
//创建第一行标题
HSSFRow row = sheet.createRow(0);
//合拼单元格
// sheet.addMergedRegion(new CellRangeAddress(0,0,0,3));
HSSFCell cell =null;
for (int i =0; i < headLists.length; i++) {
cell = row.createCell(i);
cell.setCellValue(headLists[i]);
}
System.out.println(groupList);
HSSFCell cell1=null;
for (int i =0; i < groupList.size(); i++) {
//内容区与标题距离行数
HSSFRow row1 = sheet.createRow(i+1);
//设置宽度
sheet.setColumnWidth(i,5000);
//赋值
row1.createCell(0).setCellValue(groupList.get(i).getMeId());
row1.createCell(1).setCellValue(groupList.get(i).getMeName());
row1.createCell(2).setCellValue(groupList.get(i).getUcId());
row1.createCell(3).setCellValue(groupList.get(i).getUrl());
}
}
return sheets;
}
调用方法在浏览器下载文件
@GetMapping("/menu/excel")
public JsonResult excel(HttpServletResponse response){
List groupList=projectAllService.MenuAll();
System.out.println(groupList);
HSSFWorkbook hssfWorkbook = Excels("学生表",groupList,new String[]{"id","名字","cid","url"});
OutputStream output=null;
BufferedOutputStream bufferedOutPut =null;
try {
output = response.getOutputStream();
//清缓存
response.reset();
//定义浏览器响应表头 中文需要转译加上 new String("工作网格员".getBytes(),"iso-8859-1")
response.setHeader("Content-Disposition","attachment;filename="+
new String("工作网格员".getBytes(),"iso-8859-1")+
".xlsx");
//下载文件数据过大是浏览器有限制 加上字节流长度
response.addHeader("Content-Length", String.valueOf(hssfWorkbook.getBytes().length));
//定义下载的类型,标明是excel文件
response.setContentType("application/vnd.ms-excel;utf-8");
//写入
hssfWorkbook.write(response.getOutputStream());
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
//关闭
hssfWorkbook.close();
}catch (IOException e) {
e.printStackTrace();
}
}
return hssfWorkbook!=null ? ResultUtils.ok(200,"导出成功") : ResultUtils.error(415,"导出失败");
}