java poi導出excel 表格

final String[] excelHeader = { "a", "b", "c", "d", "e",
            "f", "h" };

//接收傳入要導出參數
    @Override
    public HSSFWorkbook export(List<User> bean) {
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("用戶信息表");
        sheet.setColumnWidth(0, 20 * 256);  
        HSSFRow row = sheet.createRow((int) 0);
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
        style.setFillForegroundColor(HSSFColor.YELLOW.index);//標題背景顏色
        style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
        HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 10); //字體高度
        style.setFont(font);
        for (int i = 0; i < excelHeader.length; i++) {
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(excelHeader[i]);
            cell.setCellStyle(style);
            sheet.autoSizeColumn(i);
            sheet.setColumnWidth(i, 20 *250);  //設置表格標題寬度
        }
	
	//循環解析 傳入參數 寫入表格
        for (int i = 0; i < bean.size(); i++) {
            row = sheet.createRow(i + 1);
             User user= bean.get(i);
                row.createCell(0).setCellValue(user.getID());
            
            row.createCell(1).setCellValue(user.get(i).getname());
            row.createCell(2).setCellValue(user.get(i).getname());
            row.createCell(3).setCellValue(user.get(i).getname());
            row.createCell(4).setCellValue(user.get(i).getname());
            row.createCell(5).setCellValue(user.get(i).getname());
            row.createCell(6).setCellValue(user.get(i).getname());
        }
        return wb;
    }



Controller.java:


public void  UserExport( HttpServletRequest request,
            HttpServletResponse response){
//查詢導出數據
List<User> bean = orderService.QuerUser(id);

            HSSFWorkbook webBook = userService.export(bean); //調用導出方法
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-disposition", "attachment;filename=user.xls");
            response.setCharacterEncoding("utf-8");
            ServletOutputStream  ouputStream = response.getOutputStream();    
            webBook.write(ouputStream);  
            ouputStream.flush();    
            ouputStream.close();  
}



頁面不要用Ajax方式 不會彈出下載的
 最好直接用表單直接提交方式


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章