不用 jsp 如何返回一個頁面

答:經過將 文件 內容寫出到 ServletOutputStream 中java

例如: 在 struts中瀏覽器

    Action: app

          說明:Action中方法的返回值 String 表示要 forward 的jsp頁面,若要直接向瀏覽器寫個頁面,就直接返回voidjsp

    

//導出用戶列表
	public void exportExcel(){
		try {
			//一、查找用戶列表
			//二、導出
			HttpServletResponse response = ServletActionContext.getResponse();
			response.setContentType("application/x-execl");
			response.setHeader("Content-Disposition", "attachment;filename=" + new String("用戶列表.xls".getBytes(), "ISO-8859-1"));
			ServletOutputStream outputStream = response.getOutputStream();
			userService.exportExcel(userService.findObjects(), outputStream);
            //流用完以後要關閉
			if(outputStream != null){
				outputStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

UserService 中 exportExcel的實現:excel

   

public  void exportUserExcel(List<User> userList, ServletOutputStream outputStream) {
		try {
			//一、建立工做簿
			HSSFWorkbook workbook = new HSSFWorkbook();
			//1.一、建立合併單元格對象
			CellRangeAddress cellRangeAddress = new CellRangeAddress(0, 0, 0, 4);//起始行號,結束行號,起始列號,結束列號
			
			//1.二、頭標題樣式
			HSSFCellStyle style1 = createCellStyle(workbook, (short)16);
			
			//1.三、列標題樣式
			HSSFCellStyle style2 = createCellStyle(workbook, (short)13);
			
			//二、建立工做表
			HSSFSheet sheet = workbook.createSheet("用戶列表");
			//2.一、加載合併單元格對象
			sheet.addMergedRegion(cellRangeAddress);
			//設置默認列寬
			sheet.setDefaultColumnWidth(25);
			
			//三、建立行
			//3.一、建立頭標題行;而且設置頭標題
			HSSFRow row1 = sheet.createRow(0);
			HSSFCell cell1 = row1.createCell(0);
			//加載單元格樣式
			cell1.setCellStyle(style1);
			cell1.setCellValue("用戶列表");
			
			//3.二、建立列標題行;而且設置列標題
			HSSFRow row2 = sheet.createRow(1);
			String[] titles = {"用戶名","賬號", "所屬部門", "性別", "電子郵箱"};
			for(int i = 0; i < titles.length; i++){
				HSSFCell cell2 = row2.createCell(i);
				//加載單元格樣式
				cell2.setCellStyle(style2);
				cell2.setCellValue(titles[i]);
			}
			
			//四、操做單元格;將用戶列表寫入excel
			if(userList != null){
				for(int j = 0; j < userList.size(); j++){
					HSSFRow row = sheet.createRow(j+2);
					HSSFCell cell11 = row.createCell(0);
					cell11.setCellValue(userList.get(j).getName());
					HSSFCell cell12 = row.createCell(1);
					cell12.setCellValue(userList.get(j).getAccount());
					HSSFCell cell13 = row.createCell(2);
					cell13.setCellValue(userList.get(j).getDept());
					HSSFCell cell14 = row.createCell(3);
					cell14.setCellValue(userList.get(j).isGender()?"男":"女");
					HSSFCell cell15 = row.createCell(4);
					cell15.setCellValue(userList.get(j).getEmail());
				}
			}
			//五、輸出
			workbook.write(outputStream);
			workbook.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
相關文章
相關標籤/搜索