1. 程式人生 > >poi實現導出excel

poi實現導出excel

nbsp puts getc service quest hone obj request write

1.導入poi所需的jar包

技術分享解壓後導入其中的jar包

2.實現在瀏覽器中將查詢到的數據導入一個excel文件並實現下載(以學生表為例)

@RequestMapping("/exportStudent.action")
public void exportStudent(HttpServletResponse response) throws IOException{
List<Student> entities = studentService.getObjects();

//下載處理
//設置頭
response.setHeader("content-disposition", "attachment;filename="+System.currentTimeMillis()+".xlsx");
//獲取下載讀取的流對象
OutputStream outputStream = response.getOutputStream();

//創建一個workbook對象
Workbook wb=new XSSFWorkbook();

Sheet sheet = wb.createSheet("學生信息");

Row r0 = sheet.createRow(0);
Cell c0 = r0.createCell(0);
c0.setCellValue("序號");
Cell c1=r0.createCell(1);
c1.setCellValue("學生姓名");
Cell c2=r0.createCell(2);
c2.setCellValue("學生學號");
Cell c3=r0.createCell(3);
c3.setCellValue("卡號");
Cell c4=r0.createCell(4);
c4.setCellValue("聯系電話");
Cell c5=r0.createCell(5);
c5.setCellValue("密碼");

//行
for(int row=0;row<entities.size();row++){
Row rw = sheet.createRow(row+1);
Student student=entities.get(row);
//列
Cell cell0 = rw.createCell(0);
cell0.setCellValue(student.getId());
Cell cell1 = rw.createCell(1);
cell1.setCellValue(student.getStu_name());
Cell cell2 = rw.createCell(2);
cell2.setCellValue(student.getStu_no());
Cell cell3 = rw.createCell(3);
cell3.setCellValue(student.getCard_no());
Cell cell4 = rw.createCell(4);
cell4.setCellValue(student.getPhone());
Cell cell5=rw.createCell(5);
cell5.setCellValue(student.getPassword());

}
wb.write(outputStream);
outputStream.close();
}

3.導出表格如圖

技術分享

poi實現導出excel