JavaWeb应用之导出

574 篇文章 4 订阅

前端:

<script type="text/javascript"src="${pageContext.request.contextPath }/js/jquery.js"></script>
<form   id="queryForm" method='post'>
	<div class="layui-form-pane" style="margin-top: 15px;">
		<div class="layui-form-item">
		    <label class="layui-form-label">xx名称</label>
			<div class="layui-input-inline">
				<select name='fbean.a3' id="a3">
				 	 <option value=''>全选</option>
                	 <s:iterator value="proList" id="ml" status="proList" >
                        <option value='<s:property value="a1"/>'><s:property value="a3"/></option>
                	   </s:iterator>
				</select>
			</div>
			<label class="layui-form-label">ww编号</label>
			<div class="layui-input-inline">
				<input class="layui-input" type='text' name='fbean.a1' id='a1' value=''   onkeydown="seachD()"/>
			</div>
			<label class="layui-form-label">yy名称</label>
			<div class="layui-input-inline">
				<input class="layui-input" type='text' name='fbean.a2' id='a2' value=''   onkeydown="seachD()"/>
			</div>
		</div>
		<div class="layui-form-item">
		<!-- 
		    <label class="layui-form-label">mm编号</label>
			<div class="layui-input-inline">
				<input class="layui-input" type='text' name='fbean.a4' id='a4' value=''   onkeydown="seachD()"/>
			</div>
		 -->
			<label class="layui-form-label">nn1</label>
			<div class="layui-input-inline">
				<input class="layui-input" type='text' name='fbean.a5' id='a5' value=''   onkeydown="seachD()"/>
			</div>
			<label class="layui-form-label">rr</label>
			<div class="layui-input-inline">
				<input class="layui-input" type='text' name='fbean.a6' id='a6' value=''   onkeydown="seachD()"/>
			</div>
			<label class="layui-form-label">tt</label>
			<div class="layui-input-inline">
				<select id="a7" name="fbean.a7">
					<option value="1" selected=selected>有效</option>
					<option value="0">无效</option>
					<option value="">全部</option>
				</select>
			</div>
			<div class="layui-input-inline" style="width:80px">
				<div class="inputt" onclick="seach()">
					<input class="but-bg" type="button" value="" /><i style="position: relative;left: 30%;top: 8%;" class="layui-icon" >&#xe615;</i>
				</div>
			</div>
		</div>
	</div>
</form>

<xblock>
<button  class="layui-btn layui-btn-warm"  onclick="dcPay()"><i class="layui-icon" >&#xe642;</i>导出</button>
</xblock>
<script language="javascript">
  //导出柜台支付
function dcPay(){
 
	$.ajax({
		type: "POST",
		async: false,
		url: "<%=request.getContextPath()%>/ypay/dcPayxxxxx.action",
		data: $("#queryForm").serializeArray(),
		dataType:"json",
		error: function(){  
		   	layer.alert("操作失败", {icon: 2},function () {
                    x_admin_close();
				  
                });
        },
		success: function(data){
		  if (data) {
			    var res=data;
				if(res!=''){
			    window.location.href='<%=request.getContextPath()%>/exportExcel.action?fileName='+res;
				}else{
					layer.alert("excel导出失败!", {icon: 2},function () {
                    x_admin_close();
				  
                });
				
				}
			}
		}
		});
}

</script>

后端代码:

 //导出 
	    public String dcPayxxxx(){
	    	System.out.println("------------开始进行导出柜台支付操作---------------");
	    	String nowpage = this.getRequest().getParameter("nowpage");
			if (nowpage == null) {
				nowpage = "1";
			}
			String limit = this.getRequest().getParameter("limit");
			if (limit == null) {
				limit = "15";
			}
			fbean.setCurrentPage(Integer.parseInt(nowpage));
			fbean.setLimit(Integer.parseInt(limit));
			UserBean user = (UserBean) this.getRequest().getSession().getAttribute("user");
			     String userpk = user.getUserpk();
			try {
				fbList = ypayDao.getGtPayList(fbean);
			} catch (Exception e) {
				e.printStackTrace();
				setRequestMsg(false, "操作失败!");
				return ERROR;
			}
			//格式化时间对象
			String timeString=new SimpleDateFormat("yyyy-MM").format(new Date());
	        String filePathName="";
	    	String fileName="";
	    	try {
	    		 fileName= "DcPay"+timeString+".xls";
	    		 filePathName = getServerPath() + fileName;
	    		 //创建工作簿对象
	    		 WritableWorkbook book=Workbook.createWorkbook(new File(filePathName));
	    		 //创建工作表对象
	    		 WritableSheet sheet=book.createSheet("导出数据", 0);
	    		 //设置要显示的字段
	    		 sheet.setColumnView(0,8);
	    		 sheet.setColumnView(1,12);
	    		 sheet.setColumnView(2,18);
	    		 sheet.setColumnView(3,18);
	    		 sheet.setColumnView(4,25);
	    		 sheet.setColumnView(5,20);
	    		 sheet.setColumnView(6,20);
	    		 
	    		 
	    		 //下面是设置样式
	    	     WritableCellFormat wc = new WritableCellFormat();
	    	     wc.setAlignment(Alignment.CENTRE); // 设置居中
	    	     WritableCellFormat tms = new WritableCellFormat();
	    	     tms.setAlignment(Alignment.CENTRE); // 设置居中
	    	     WritableFont wf = new WritableFont(WritableFont.COURIER, 13,WritableFont.NO_BOLD, false);
	    	     WritableCellFormat top = new WritableCellFormat(wf);
	    	     top.setAlignment(Alignment.CENTRE); // 设置居中
	    	     top.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//垂直居中
	    	     WritableFont fo = new WritableFont(WritableFont.COURIER, 12,WritableFont.NO_BOLD, false);
	    	     WritableCellFormat top1 = new WritableCellFormat(fo);
	    	     top1.setAlignment(Alignment.CENTRE); // 设置居中
	    	     top1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);//垂直居中
	    	    	  Label label5=new Label(0,0,"柜台收款",top);
	    	    	  sheet.mergeCells(0,0,6,0);//合并单元格
	    	    	  sheet.addCell(label5);
	    	    	  //创建单元格对象
	    	    	  Label label6=new Label(0,1,"序号",top1);
	    	    	  Label label7=new Label(1,1,"项目名称",top1);
	    	    	  Label label8=new Label(2,1,"用户编号",top1);
	    	    	  Label label9=new Label(3,1,"用户名称",top1);
	    	    	  Label labe20=new Label(4,1,"银行卡号",top1);
	    	    	  Label labe21=new Label(5,1,"充值总金额",top1);
	    	    	  Label labe22=new Label(6,1,"剩余金额",top1);
	    	    	 //添加单元格
	    	    	  sheet.addCell(label6);  sheet.addCell(label7);
	    	    	  sheet.addCell(label8);  sheet.addCell(label9);
	    	    	  sheet.addCell(labe20);  sheet.addCell(labe21);
	    	    	  sheet.addCell(labe22);
	    	    	  //往单元格填充对象
	    				  for(int i=0;i<fbList.size();i++){
	    					  Label lab0 =new Label(0,i+2,String.valueOf(i+1),wc);
	    					  Label lab1 =new Label(1,i+2,fbList.get(i).getA1(),wc);
	    					  Label lab2 =new Label(2,i+2,fbList.get(i).getA2(),wc);
	    					  Label lab3 =new Label(3,i+2,fbList.get(i).getA4(),wc);
	    					  Label lab4 =new Label(4,i+2,fbList.get(i).getA6(),wc);
	    					  Label lab5 =new Label(5,i+2,fbList.get(i).getA7(),wc);
	    					  Label lab6 =new Label(6,i+2,fbList.get(i).getA8(),wc);
	    					  
	    					  sheet.addCell(lab0);
	    					  sheet.addCell(lab1);
	    					  sheet.addCell(lab2);
	    					  sheet.addCell(lab3);
	    					  sheet.addCell(lab4);
	    					  sheet.addCell(lab5);
	    					  sheet.addCell(lab6);	
	    			       }
	    				  book.write();
	    				  book.close();
	    				  System.out.println("成功!!!!");
	    		    }catch (Exception e) {
	    				 setRequestMsg(false,"操作失败");
	    				 this.writeJSON(false);
	    			 }
//	    			 setRequestMsg(true, new File(filePathName).getName()); 		
   			 this.writeJSON(new File(filePathName).getName());
	    	return SUCCESS;
	    }
	 
	public void writeJSON(Object o){
		//将对象转换为JSON
		String json=JSONObject.toJSONString(o);
		try {
			//设置编码
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().println(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	<!--下载导出excel-->
		<action name="exportExcel" class="com.common.util.CommonExportAction">
			<result name="success" type="stream">
				<param name="contentType">
					application/vnd.ms-excel
				</param>
				<param name="inputName">inputStream</param>
				<param name="contentDisposition">
					attachment;filename="${downloadFileName}"
				</param>
				<param name="bufferSize">4096</param>
			</result>
		</action>
package com.common.util;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import com.common.BaseAction;

public class CommonExportAction extends BaseAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = -4154705339330040142L;
	private String fileName;

	public InputStream getInputStream() throws Exception {
		String filePath = new String(getServerPath() + fileName);
		InputStream in = getDownloadFile(filePath, null);
		if (FileUtil.isFileExisted(filePath)) {
			FileUtil.deleteFile(filePath);
		}
		return in;
	}

	public String execute() throws Exception {
		fileName = getDownloadFileName();
		return SUCCESS;
	}

	/**
	 * 得到系统布署路径.<br>
	 * 工程名:cctceb<br>
	 * 包名:com.cctchina.warehouse.action<br>
	 * 方法名:getServerPath方法.<br>
	 * 
	 * @author:ZW
	 * @since :2011-02-15
	 * @return
	 */
	public String getServerPath() {
		return getRequest().getRealPath("/");
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getDownloadFileName() {
		String downFileName = fileName;
		try {
			downFileName = new String(downFileName.getBytes(), "ISO8859-1");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return downFileName;

	}

	public InputStream getDownloadFile(String realPath, byte[] fileContents)
			throws Exception {
		InputStream stream = null;
		if (realPath == null && fileContents == null) {
			return null;
		}
		if (realPath != null && !"".equals(realPath)) {

			try {
				File readFile = new File(realPath);
				FileInputStream fis = new FileInputStream(readFile);
				byte[] buffer = new byte[(int) readFile.length()];
				fis.read(buffer);
				fis.close();
				stream = new ByteArrayInputStream(buffer);
			} catch (FileNotFoundException e) {
				throw e;
			}
		} else {
			stream = new ByteArrayInputStream(fileContents);
		}
		return stream;
	}

	public String getFileName() {
		return fileName;
	}
}

package com.common;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.alibaba.fastjson.JSONObject;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 公用ACTION
 * 
 */
@SuppressWarnings("serial")
public class BaseAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware {
	@SuppressWarnings("unused")
	private HttpServletRequest request; // 请求
	@SuppressWarnings("unused")
	private HttpServletResponse response;
	private String message; // 消息显示
	private Boolean success; // 是否成功
	private String jsonList;
	private String limit;
	private String start;
	private String guidePage;

	public void setServletRequest(HttpServletRequest request) {
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response) {
		this.response = response;

	}

	public HttpServletRequest getRequest() {
		return ServletActionContext.getRequest();
	}

	public HttpServletResponse getResponse() {
		return ServletActionContext.getResponse();
	}

	public Boolean getSuccess() {
		return success;
	}

	public void setSuccess(Boolean success) {
		this.success = success;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public void setRequestMsg(Boolean success, String message) {
		this.setSuccess(success);
		this.setMessage(message);
	}
	public void writeJSON(Object o){
		//将对象转换为JSON
		String json=JSONObject.toJSONString(o);
		try {
			//设置编码
			response.setContentType("text/html;charset=utf-8");
			response.getWriter().println(json);
			response.getWriter().flush();
			response.getWriter().close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	/**
	 * 得到当前页
	 * 
	 * @return
	 */
	public int getCurrrentPage() {
		int currPage = 0;
		currPage = (Integer.parseInt(this.getStart()))
				/ (Integer.parseInt(this.getLimit()));
		if (currPage == 0) {
			currPage = 1;
		} else {
			currPage = currPage + 1;
		}
		return currPage;
	}

	/**
	 * 得到系统路径
	 * 
	 * @return
	 */
	public String getServerPath() {
		return getRequest().getRealPath("/");
	}

	public String getJsonList() {
		return jsonList;
	}

	public void setJsonList(String jsonList) {
		this.jsonList = jsonList;
	}

	public String getLimit() {
		return limit;
	}

	public void setLimit(String limit) {
		this.limit = limit;
	}

	public String getStart() {
		return start;
	}

	public void setStart(String start) {
		this.start = start;
	}

	public String getGuidePage() {
		return guidePage;
	}

	public void setGuidePage(String guidePage) {
		this.guidePage = guidePage;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值