Java 实现生成Excel,以下载方式返回浏览器本地

简述:

实现访问一个service, 返回相应数据的Excel返回本地(下载)


步骤:

1.首先需要导入excel的包,此处添加Maven的依赖项

		
			net.sourceforge.jexcelapi
			jxl
			2.6.12
		



Spring中的servlet映射, 包括文件流的形式返回

	/**
	 * 输出活动到Excel文件
	 * @param request
	 * @param response
	 */
	public void exportOneActivityToExcel(HttpServletRequest request
			, HttpServletResponse response){
		String activityId = request.getParameter("activityId");
		if(activityId == null || activityId == ""){
			logger.error("活动ID为空");
			 response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		
		SignActivity activity = signActivityService.getSignActivityById(activityId);
		
		File outputFile = signActivityService.exportActivityToExcelById(activity
				, this.getServletContext().getRealPath("/upload/excelFile/"));
		
		//返回excel的文件流
		try {
			response.reset();// 清空输出流
			response.setHeader("Content-disposition", "attachment; filename=sign_activity"
			    + new SimpleDateFormat("yyyyMMdd_HHmmssSSS")
			              .format(new Date()) +".xls");// 设定输出文件头
			response.setContentType("application/msexcel");// 定义输出类型

			// 读取文件并且输出
			FileInputStream fin = new FileInputStream(outputFile);
			byte[] tempBytes = new byte[2048];
			while (fin.read(tempBytes) != -1) {
				response.getOutputStream().write(tempBytes);
			}
			response.getOutputStream().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

service层调用了自己用jxl实现的工具类的生成excel方法

	/**
	 * 导出活动的Excel表
	 * @param activityId
	 * @return
	 */
	public File exportActivityToExcelById(final SignActivity activity, final String filePath) {
		File excelFile = ExcelUtilProcess.exportOneSignActivity(activity, filePath) ;
		return excelFile;
	}


工具类中生成Ecel,返回FIle文件形式

	public static File exportOneSignActivity(SignActivity activity, final String filePath){
		File tempFileDir = new File(filePath);
		if(!tempFileDir.exists()){
			tempFileDir.mkdirs();
			logger.debug("创建临时文件目录");
		}
		
		File tempExcelFile=new File(tempFileDir, "sign_activity_" + activity.getId()+".xls");
		if(tempExcelFile.exists()){
			tempExcelFile.delete();
			logger.debug("删除同名Excel文件");
		}
		
		try {
			tempExcelFile.createNewFile();
			logger.debug("创建Excel文件" + tempExcelFile.getPath());
			WritableWorkbook workBook=Workbook.createWorkbook(tempExcelFile);
			WritableSheet sheet=workBook.createSheet("活动名单", 0);
			logger.debug("创建工作表");
			
			WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16,
			WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.BLACK);
			WritableCellFormat wcfFC = new WritableCellFormat(wfont);
			wcfFC.setBackground(Colour.AQUA);
			wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14,
					WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
					Colour.BLACK);
			wcfFC = new WritableCellFormat(wfont);
			
			//插入标题 
			sheet.addCell(new Label(0, 0, "名称"));   
			sheet.addCell(new Label(1, 0, "描述"));   
			sheet.addCell(new Label(2, 0, "地址"));
			sheet.addCell(new Label(3, 0, "发布日期"));
			sheet.addCell(new Label(4, 0, "开始日期"));
			sheet.addCell(new Label(5, 0, "结束日期"));
			logger.debug("插入标题");
			
			//添加传入的签到活动数据
			int rowIndex=1;
			sheet.addCell(new Label(0, rowIndex, activity.getName()));
			sheet.addCell(new Label(1, rowIndex, activity.getDescription()));
			sheet.addCell(new Label(2, rowIndex, activity.getSignAddress()));
			sheet.addCell(new Label(3, rowIndex,
					new SimpleDateFormat("yyyy-MM-dd").format(activity.getPublishTime())));
			sheet.addCell(new Label(4, rowIndex,
					new SimpleDateFormat("yyyy-MM-dd").format(activity.getStartTime())));
			sheet.addCell(new Label(5, rowIndex,
					new SimpleDateFormat("yyyy-MM-dd").format(activity.getEndTime())));
			logger.debug("导出Excel文件完成");
			
			// 写入Excel对象
			workBook.write();
			workBook.close();
			logger.debug("释放资源");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (WriteException e) {
			e.printStackTrace();
		}
		return tempExcelFile;
	}

下面是前端调用后台service的实现


/**
 * 获取当前部署项目的url
 * 例如: 
 * http://192.168.2.199://8087/myWebProject
 */
function GetContextPath(){
	var localObj = window.location;
    var contextPath = localObj.pathname.split("/")[1];
    var basePath = localObj.protocol+"//"+localObj.host+"/"+contextPath;
    return basePath;
}

/**
 * 导出单条活动
 */
function outputActivity(activityId){
	var action = 'exportOneActivityToExcel';
	window.location.href = GetContextPath() + "/business/activity?action="
			+ action + "&activityId=" + activityId;
}




你可能感兴趣的:(Java,Web,Java)