Controller层代码如下:
@Controller
public class ExportController{
@Autowired
private ExportService exportService;
@RequestMapping(value = "/export/excel")
public void exportExcel(HttpServletRequest request, HttpServletResponse response)
throws Exception {
//生成一个列表信息
List<Student> list = new ArrayList<Student>();
list.add(new Student(0001,"童年","22","男"));
list.add(new Student(0002,"光光","23","女"));
list.add(new Student(0003,"丁丁","21","男"));
XSSFWorkbook wb = exportService.export(list);
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment;filename=student.xlsx");
OutputStream ouputStream = response.getOutputStream();
wb.write(ouputStream);
ouputStream.flush();
ouputStream.close();
}
}
Service层代码如下:
@Service
public class ExportService {
//定义表头
String[] excelHeader = {"学号", "姓名", "年龄","性别"};
public XSSFWorkbook export(List<Campaign> list) {
//这里需要说明一个问题:如果是 Offices 2007以前的Excel版本,new的对象是:**HSSFWorkbook** ,Offices 2007以后的Excel版本new的对象才是XSSFWorkbook
XSSFWorkbook wb = new XSSFWorkbook();
//生成一个工作表
Sheet sheet = wb.createSheet("学生表");
//生成第一行
Row row = sheet.createRow((int) 0);
//生成单元格的样式style
XSSFCellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_CENTER);
for (int i = 0; i < excelHeader.length; i++) {
//获取每一个单元格
Cell cell = row.createCell(i);
//给单元格赋值
cell.setCellValue(excelHeader[i]);
//设置单元格的样式
cell.setCellStyle(style);
}
for (int i = 0; i < list.size(); i++) {
//得到当前行数的下一行(row.getRowNum():得到当前行数)
row = sheet.createRow(row.getRowNum() + 1);
Student student = list.get(i);
//赋值
row.createCell(0).setCellValue(student.getSno());
row.createCell(1).setCellValue(student.getName());
row.createCell(2).setCellValue(student.getAge());
row.createCell(3).setCellValue(student.getSex());
}
return wb;
}
}