谁用过JSF加POI导出excel的操作,我这为什么浏览器不会下载?

奔跑的码农 发布于 2017/08/25 18:34
阅读 72
收藏 0
/**
	 * 导出Excel
	 * @param outputStream 文件写入到输出流
	 * @param list	需要生成Excel的list
	 */
	public static <E> void createExcel(OutputStream outputStream,List<E> list){
		//创建HSSFWorkBook(也就是excel文件)
		HSSFWorkbook workbook=new HSSFWorkbook();
		//创建一个SHEET
		HSSFSheet sheet=workbook.createSheet();
		Object element=list.get(0);	
		//初始化表格列名以及表格样式(宽度)
		int columnIndex=0;
		int rowIndex=0;
		HSSFRow row=sheet.createRow(rowIndex++);
		for(Field field:element.getClass().getDeclaredFields()){
			field.setAccessible(true);
			if (field.getAnnotation(Excel.class)==null)
				continue;
			String titleName=field.getAnnotation(Excel.class).name();
			int width=field.getAnnotation(Excel.class).width();
			if (width!=0) {
				sheet.setColumnWidth(columnIndex, width);
			}else {
				sheet.setColumnWidth(columnIndex, titleName.getBytes().length*2*256);
			}
			row.createCell(columnIndex).setCellValue(titleName);
			columnIndex++;
		}
		columnIndex=0;
		//遍历LIST
		for(Object entity:list){
			HSSFRow valueRow=sheet.createRow(rowIndex++);
			for(Field field:entity.getClass().getDeclaredFields()){
				field.setAccessible(true);
				if (field.getAnnotation(Excel.class)==null)
					continue;
				try {
					String value=field.get(entity).toString();
					valueRow.createCell(columnIndex).setCellValue(value);
				} catch (IllegalArgumentException | IllegalAccessException e) {
					e.printStackTrace();
				}
			}
			columnIndex=0;
		}
		try {
			workbook.write(outputStream);
			outputStream.flush();
			outputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

JSF

//用来导出excel文件
	public void downloadExcel() throws IOException{
		FacesContext ctx =FacesContext.getCurrentInstance();
		ctx.responseComplete();
		HttpServletResponse response=this.getResponse();
		response.reset();
		response.setContentType("application/octet-stream");  
         response.setHeader("Content-disposition","attachment;filename="+URLEncoder.encode("测试.xls","utf-8"));   
         response.setCharacterEncoding("UTF-8");
         ExcelUtil.createExcel(response.getOutputStream(), inControlSupplierListDataModel.getExcelList()); 
         response.flushBuffer();
	}

 

加载中
0
奔跑的码农
奔跑的码农

问题已经解决,ajax忘了设置成false

返回顶部
顶部