zoukankan      html  css  js  c++  java
  • java、jsp导出excel功能备份

    问题踩坑:

    ajax请求不能下载文件

    必须这样:

    <a href="/media">点击下载Excel</a>

    或者

    location.href = '/media';

    js取表单数据:

    var selectbatch = $("selectbatch").value

    java代码:

    package com.action;

     

    import java.io.ByteArrayInputStream;

    import java.io.ByteArrayOutputStream;

    import java.io.IOException;

    import java.io.InputStream;

    import java.text.SimpleDateFormat;

    import java.util.ArrayList;

    import java.util.Date;

    import java.util.List;

     

    import javax.servlet.ServletException;

    import javax.servlet.ServletOutputStream;

    import javax.servlet.http.HttpServletRequest;

    import javax.servlet.http.HttpServletResponse;

     

    import org.apache.log4j.Logger;

     

    import com.IHttpAction;

    import com.sql.ExchangeSql;

     

    import jxl.Workbook;

    import jxl.write.Label;

    import jxl.write.NumberFormats;

    import jxl.write.WritableCell;

    import jxl.write.WritableCellFormat;

    import jxl.write.WritableSheet;

    import jxl.write.WritableWorkbook;

    import jxl.write.WriteException;

    import jxl.write.biff.RowsExceededException;

     

    /**

     * @FileName:     ExchangeSelectAction.java

     * @Description:  

     * @Author  :     xingchong

     * @CreateTime:   Nov 15, 2018 8:42:45 PM

     * @Copyright:    Copyright (c) 2017

     * @Version:      1.0

     */

    public class ExchangeExportAction implements IHttpAction {

     

    private ExchangeSql exchangeSql = new ExchangeSql();

     

    private Logger logger = Logger.getLogger(ExchangeExportAction.class);

     

    /* (non-Javadoc)

    * @see com.gm.console.IHttpAction#action(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)

    */

    @Override

    public void action(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    int batch = Integer.parseInt(request.getParameter("selectbatch"));

    logger.info("selectbatch = "+ batch);

    try {

    InputStream is = this.exportExchangeCode(batch);

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");

    String fileName = "batch_"+batch+"_"+sdf.format(new Date()) + ".xls";

     

    response.setContentType("applicaiton/x-download"); 

        response.addHeader("Content-Disposition", "attachment;filename="+fileName); 

     

    ServletOutputStream out=response.getOutputStream();

    int len=0;

    byte[] buffer=new byte[1024];

    while((len=is.read(buffer))>0){

    out.write(buffer,0,len);

    }

    is.close();

    out.close();

    // response.getWriter().write("<span>export excel ok...</span>");

    } catch (Exception e) {

    e.printStackTrace();

    }

    }

     

    /**

    * 获取兑换码html信息

    * 

    * @param batch

    * @return

    * @throws Exception

    */

    private InputStream exportExchangeCode(int batch) throws Exception {

    List<List<String>> dataList = null;

    if (batch > 0) {

    dataList = this.exchangeSql.getExchangeData(batch, Integer.MAX_VALUE);

    } else {

    dataList = this.exchangeSql.getSimpleExchangeData(Integer.MAX_VALUE);

    }

    List<String> titleList = dataList.get(0);

    dataList.remove(0);

    InputStream is = null;

    try {

    ByteArrayOutputStream os = new ByteArrayOutputStream();

    WritableWorkbook wwb = Workbook.createWorkbook(os);

    int step = 50000;

    int size = dataList.size();

    int sheetIndex = 0;

    for(int start = 0; start < size; start+=step){

    int end = start + step;

    end = end > size? size:end;

    List<List<String>> dataListSub = new ArrayList<List<String>>();

    dataListSub.add(titleList);

    dataListSub.addAll(dataList.subList(start, end));

    this.writeDataToSheet(wwb, dataListSub, sheetIndex++);

    }

    wwb.write();

    wwb.close();

    is = new ByteArrayInputStream(os.toByteArray());

    } catch (IOException e) {

    e.printStackTrace();

    } catch (WriteException e) {

    e.printStackTrace();

    }

    return is;

    }

     

    /**

    * 写一页excel

    * @param wwb

    * @param dataList

    * @param sheetIndex

    * @throws RowsExceededException

    * @throws WriteException

    */

    private void writeDataToSheet(WritableWorkbook wwb, List<List<String>> dataList, int sheetIndex)

    throws RowsExceededException, WriteException {

    WritableSheet sheet = wwb.createSheet("data_"+sheetIndex, sheetIndex);

    WritableCellFormat wcf = new WritableCellFormat(NumberFormats.TEXT);

    for (int r = 0; r < dataList.size(); r++) {

    List<String> list = dataList.get(r);

    for (int c = 0; c < list.size(); c++) {

    String string = list.get(c);

    WritableCell writableCell = new Label(c, r, string, wcf);

    sheet.addCell(writableCell);

    }

    }

    }

     

    }

    jsp代码:

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>

    <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt"%>

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

    <HTML>

    <HEAD>

    <title>My JSP 'buildinglist.jsp' starting page</title>

    <meta http-equiv="pragma" content="no-cache">

    <meta http-equiv="cache-control" content="no-cache">

    <meta http-equiv="Content-type" content="text/html charset=utf-8">

    <meta http-equiv="expires" content="0">

    <LINK href="/console/style/default.css" type=text/css rel=stylesheet>

    <LINK href="/console/style/style.css" type=text/css rel=stylesheet>

    <LINK href="/console/style/style3.css" type=text/css rel=stylesheet>

    <LINK href="/console/style/tab.webfx.css" type=text/css rel=StyleSheet>

    <link href="/console/style/calendar.css" type=text/css rel=StyleSheet>

    <script type="text/javascript" src="/console/js/prototype.js"></script>

    <script type="text/javascript" src="/console/js/tools.js"></script>

    <script type="text/javascript" src="/console/js/calendar.js"

    charset="utf-8"></script>

    <script type="text/javascript" src="/console/js/swfobject.js"

    charset="utf-8"></script>

     

    <script type="text/javascript">

    function btnAjax() {

    $("resultTable").innerHTML = "<span style="color: red;">正在紧张生成中...请勿重复点击...</span>";

    var myAjax = new Ajax.Request("customRequest.htm?catalog=exchange_add",

    {

    method : 'post',

    parameters : Form.serialize('Form1'),

    onComplete : function(x) { //提交成功回调 

    $("resultTable").innerHTML = x.responseText;

    },

    onError : function(x) { //提交失败回调

    alert(x.statusText);

    }

    });

    }

     

    function selectAjax() {

    $("selectTable").innerHTML = "<span style="color: green;">正在查询中...请稍等...</span>";

    var myAjax = new Ajax.Request(

    "customRequest.htm?catalog=exchange_select", {

    method : 'post',

    parameters : Form.serialize('Form1'),

    onComplete : function(x) { //提交成功回调 

    $("selectTable").innerHTML = x.responseText;

    },

    onError : function(x) { //提交失败回调

    alert(x.statusText);

    }

    });

    }

     

    //export excel

    function exportExcel() {

    var selectbatch = $("selectbatch").value

    location.href = '/customRequest.htm?catalog=exchange_export&selectbatch='+selectbatch;

    }

     

    </script>

    <style type="text/css">

    </style>

    </HEAD>

    <body>

    <form id="Form1" name="Form1" method="post">

    <div style="clear: both; height: 1px; overflow: hidden"></div>

     

    <div width="98%" align="left" valign="left">

    <font size="6px"> <br>兑换码生成 <br>

    <br>

    </font> ${result}

    </div>

     

     

    <table align="left" class=detail>

    <tbody>

    <tr>

    <td class="list_td01">类型</td>

    <td><select name="codeType">

    <option value="1">单人单次</option>

    <option value="0">多人共享单次</option>

    </select> <span style="color: red;">1-单人单次 0-多人单次</span></td>

     

    <td class=list_td01>生成数量</td>

    <td class=list_td02><select name="num">

    <option value="10">10</option>

    <option value="100">100</option>

    <option value="1000">1000</option>

    <option value="10000">10000</option>

    <option value="100000">100000</option>

    </select></td>

     

    </tr>

    <tr align="left">

    <td class="list_td01">开始时间</td>

    <td class="list_td02"><input type="text"

    onclick="displayCalendar(this,'yyyy-mm-dd hh:ii:00',this,true);"

    class="datetime" id="startTime" name="startTime"> <span

    style="color: red;">(必须)</span></td>

     

    <td class="list_td01">结束时间</td>

    <td class="list_td02"><input type="text"

    onclick="displayCalendar(this,'yyyy-mm-dd hh:ii:00',this,true);"

    class="datetime" id="endTime" name="endTime"> <span

    style="color: red;">(必须)</span></td>

    </tr>

     

    <tr>

    <td class=list_td01>奖励Json</td>

    <td class=list_td02 colspan="3"><input type="text" size=90

    name="rewardJson" id="rewardJson" value=""> <span

    style="color: red;">(必须)</span></td>

    </tr>

     

    <tr>

    <td class=list_td01>等级限制</td>

    <td class=list_td02 colspan="1"><select name="level">

    <option value="1">1级</option>

    <option value="10">10级</option>

    <option value="20">20级</option>

    <option value="30">30级</option>

    <option value="40">40级</option>

    <option value="50">50级</option>

    <option value="60">60级</option>

    <option value="70">70级</option>

    <option value="80">80级</option>

    <option value="90">90级</option>

    <option value="100">100级</option>

    <option value="110">110级</option>

    <option value="120">120级</option>

    </select></td>

     

     

    <td class=list_td01>生成批次</td>

    <td class=list_td02 colspan="1"><input type="text" size=20

    name="batch" id="batch" value="1"> <span

    style="color: red;">(必须)</span></td>

    </tr>

     

     

    <tr>

    <td align="left"><input type="button" class="butcom"

    onclick="btnAjax()" value=" 生成提交 " /></td>

    </tr>

    </table>

     

    <TABLE id="resultTable" align="left" class=common></TABLE>

     

     

    <!-- select about -->

    <table align="left" class=detail>

    <tr>

    <td class=list_td01>批次 </td>

    <td class=list_td02><input type="text" size=10 name="selectbatch"

    id="selectbatch" value="0"> <span

    style="color: green;">(0表求所有批次)</span></td>

     

     

    <td align="left"><input type="button" class="butcom"

    onclick="selectAjax()" value="  查询  " /></td>

     

    <td align="left"><input type="button" class="butcom"

    onclick="exportExcel()" value="  导出excel  " /></td>

    </tr>

    </table>

     

    <TABLE id="selectTable" align="left" class=common></TABLE>

     

    </form>

    </body>

    </HTML>

  • 相关阅读:
    4270. 【NOIP2015模拟10.27】魔道研究
    4269. 【NOIP2015模拟10.27】挑竹签
    NOIP2015模拟10.28B组
    JZOI5257. 小X的佛光
    4260. 最大子矩阵 (Standard IO)
    1010. 【CQOI2009】叶子的颜色
    【NOIP2015模拟10.22】最小代价
    JZOI 距离 (Standard IO) 题解
    统计和 luogu P2068 树状数组和线段树练手
    2020.7.15模拟赛
  • 原文地址:https://www.cnblogs.com/xingchong/p/10003243.html
Copyright © 2011-2022 走看看