public String exportExcelList(){ //創建webbook,對應一個excel文件 HSSFWorkbook wb = new HSSFWorkbook(); //在webbook中添加一個sheet,對應excel中的sheet HSSFSheet sheet = wb.createSheet("檢查單"); //在sheet中添加表頭,添加一行 HSSFRow row = sheet.createRow(0); //設置每一列的寬,此處可根據實際情況設置. sheet.setColumnWidth(1, 20*256); sheet.setColumnWidth(6, 20*256); sheet.setColumnWidth(7, 20*256); sheet.setColumnWidth(8, 20*256); sheet.setColumnWidth(11, 20*256); sheet.setColumnWidth(12, 20*256); sheet.setColumnWidth(13, 20*256); //設置表格樣式 HSSFCellStyle style = wb.createCellStyle(); style.setAlignment(HSSFCellStyle.ALIGN_LEFT);//內容向左靠齊 Font font = wb.createFont();//為字體設計樣式 font.setFontHeightInPoints((short)12); //字體大小 font.setFontName("宋體"); style.setFont(font);//將字體加入到表格樣式中 //設置列名稱(第一列) HSSFCell cell = row.createCell(0); cell.setCellValue("id");//列名稱 cell.setCellStyle(style);//列樣式 //第二列 cell = row.createCell(1); cell.setCellValue("syncDate"); cell.setCellStyle(style); ......... //查出你要的數據 List laboratoryList = laboratoryInformationService.getInformationByTime(timeHelper); //遍歷數據 for(int i=0;i<laboratoryList.size();i++){ //創建行 row = sheet.createRow(i+1); Map<String,Object> laboratoryMap = new HashMap<String,Object>();//臨時變量 laboratoryMap = (Map<String, Object>) laboratoryList.get(i); //給每一行設置單元格 //第一列 cell = row.createCell(0);//列索引 cell.setCellValue(laboratoryMap.get("id").toString());//單元格內容 cell.setCellStyle(style);//列的樣式 //第二列 cell = row.createCell(1); cell.setCellValue(laboratoryMap.get("syncDate").toString()); cell.setCellStyle(style); ............ } //將excel的數據寫入文件 HttpServletResponse res = ServletActionContext.getResponse(); res.setContentType("octets/stream"); String excelName = "檢查單";//文件名字 //轉碼防止亂碼 try { res.addHeader("Content-Disposition", "attachment;filename="+new String( excelName.getBytes("gb2312"), "ISO8859-1" )+".xls"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } OutputStream os; try { os = res.getOutputStream(); wb.write(os); os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("excel導出成功"); return null;//此處一定要為null否則報錯 }