public voiddownXls(HttpServletRequest request , HttpServletResponse response) throws ServletException, IOException, BiffException{
- //得到數據裏面的內容,可以確定要導出哪些數據,要導出哪些字段,要導入什麼信息
List<Emps> empList = empService.getAllEmps();
HSSFWorkbook wb = new HSSFWorkbook();//新建一個workBook,這裏就相當於一個excel文件
HSSFSheet sheet =wb.createSheet();//創建一個工作簿
//設置每列的寬度
sheet.setColumnWidth(0, 2000);
sheet.setColumnWidth(1, 4000);
sheet.setColumnWidth(2, 5000);
//字體
HSSFFont font = workbook.createFont();
font.setBoldweight((short)1000);
font.setFontName("隸書");
font.setFontHeightInPoints((short)15); //設置字體大小
//單元格樣式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFont(font);
//給每個單元格指定樣式以及內容
HSSFCell cell0 = titleRow.createCell(0);
cell0.setCellStyle(cellStyle);
cell0.setCellValue(new HSSFRichTextString("職工號"));
HSSFCell cell1 = titleRow.createCell(1);
cell1.setCellStyle(cellStyle);
cell1.setCellValue(new HSSFRichTextString("職工姓名"));
HSSFCell cell2 = titleRow.createCell(2);
cell2.setCellStyle(cellStyle);
cell2.setCellValue(newHSSFRichTextString("部門名字"));
int num = empList.size();
for(int i = 1 ; i< num ; i++){
HSSFRow row =sheet.createRow(i);//創建行
row.createCell((short)0).setCellValue(newHSSFRichTextString(empList.get(i-1).getEmpId()+""));//設置沒一行每個單元格的值
row.createCell((short)1).setCellValue(newHSSFRichTextString(empList.get(i-1).getEmpName()));
row.createCell((short)2).setCellValue(newHSSFRichTextString(empList.get(i-1).getDep().getDepName()));
}
//增加一個最後一行
HSSFRow row = sheet.createRow(num+1);
HSSFCell footCell = row.createCell(0);
footCell.setCellValue(new HSSFRichTextString("合計:"));
//設置最後一行的樣式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_LEFT); //內容左對齊
footCell.setCellStyle(style);
//合併單元格(第一個單元格的行數,第二個單元格的行數,第一個單元格的列,第二個單元格的列)
sheet.addMergedRegion(newCellRangeAddress(num+1,num+1,0,2));
//導出成excel形式的,用流的形式下載的方式
response.addHeader("Content-Disposition", "attachment;filename=myFile.xls");
response.addHeader("Content-type", "application/vnd.ms-excel");
try{
OutputStream os =response.getOutputStream();
wb.write(os);
os.close();
}catch(Exception e){
e.printStackTrace();
}
}