码迷,mamicode.com
首页 > Web开发 > 详细

(四)Web应用开发---导出到Excel

时间:2016-03-12 13:13:48      阅读:335      评论:0      收藏:0      [点我收藏+]

标签:

导出到Excel、UI设计类如

技术分享

  • Copy样例Html代码到新建Html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>盘点数据查询 v2.0</title>
    <script src="/Scripts/jquery-1.8.2.min.js"></script>
    <script src="/Scripts/wrap/jquery.easyui.min.js"></script>
    <script src="/scripts/wrap/locale/easyui-lang-zh_CN.js"></script>
    <script src="/Scripts/datasrvrequest.js"></script>
    <script src="/Scripts/json2.js"></script>
    <link href="/Scripts/wrap/themes/icon.css" rel="stylesheet" />
    <link href="/scripts/wrap/themes/default/easyui.css" rel="stylesheet" />

    <script type="text/javascript" language="javascript">
        var editIndex = undefined;
        function grid_load_callback(data, status) {
            $("#dg").datagrid("loadData", data);

        }
        function grid_load(pageindex, pagesize) {
            if (pageindex == null)
                pageindex = 1;
            if (pagesize == null)
                pagesize = 20;
            var ph = new parmHelper();

            var logun = request("userno");
            var sn = $.getJquery("ddlsnlist").combobox("getValue");
            var flag = $.getJquery("ddlstatuslist").combobox("getValue");
            if (flag == "") flag = -2;
            var cc = $.getValue("txtcostcenter");
            var fno = $.getValue("txtfano");
            ph.Add("userno", logun);
            ph.Add("sn", sn);
            ph.Add("cc", cc);
            ph.Add("fano", fno);
            
            ph.Add("flags", flag);
            ph.Add("sortfields", "");

            ph.Add("pagesize", pagesize);
            ph.Add("pageindex", pageindex);
            var p = JSON2.stringify(ph.KeyValueArray);
            retrieveJsonData("/FADB/GetPagerDSJson", p, "510624862", grid_load_callback);//405576483
        }

        function btnsearch_click() {
            grid_load(0, 20);
        }

        function initGrid(grid) {
            getjquery(‘dg‘).datagrid({
                //title: ‘CheckBox Selection on DataGrid‘,
                url: ‘‘,
                width: ‘700‘,
                rownumbers: true,
                pageList: [20, 60, 100],
                columns: [[
                { field: ‘rowid‘, width: 20 },
                { field: ‘sn‘, title: ‘申请单号‘, width: 100 },
                { field: ‘FANO‘, title: ‘资产编号‘, width: 100 },
                { field: ‘FAName‘, title: ‘名称‘, width: 100 },
                { field: ‘CostCenter‘, title: ‘费用代码‘, width: 100 },
                { field: ‘Location‘, title: ‘存放位置‘, width: 500 },
                { field: ‘flag‘, title: ‘状态‘, width: 80 },
                { field: ‘CreateTime‘, title: ‘创建时间‘, width: 130 }
                ]],
                fit: true,
                singleSelect: true,
                //selectOnCheck: false,
                //checkOnSelect: false,
                striped: true, //行背景交换
                nowap: true, //列内容多时自动折至第二行

                pagination: true,
                rowStyler: function (index, row) {
                    //if (index%2==0) {
                    //    return ‘background-color:#6293BB;color:#fff;‘;
                    //}
                }

            });

        }
        //初始化盘点清单回调
        function datachange_callback(data, status) {
            if (data.length > 0 && data[0].tcount > 0) {
                $.messager.alert(‘操作结果提示‘, ‘操作执行成功!‘, ‘info‘);
                grid_load(0, 20);
            }
            else
                $.messager.alert(‘操作结果提示‘, ‘操作执行失败!‘, ‘error‘);
        }

        function initGridPager() {
            var grid = getjquery("dg");
            var p = grid.datagrid("getPager");
            (p).pagination({
                onSelectPage: function (pageNumber, pageSize) {
                    grid_load(pageNumber, pageSize);
                }

            });
        }

        function ddlbind_callback(data, status) {
            getjquery("ddlsnlist").combobox("loadData", data);
        }
        function bindSNComboBoxList() {
            retrieveJsonData("/FADB/GetDTJson", "", "270624007", ddlbind_callback);
        }
        function bindStatusComboBoxList() {
            retrieveJsonData("/FADB/GetDTJson", "", "791673868", function (data, status) { getjquery("ddlstatuslist").combobox("loadData", data); });
        }
        $(function () {
            //读取数据
            getjquery("btnsearch").bind("click", btnsearch_click);
            bindSNComboBoxList();
            bindStatusComboBoxList();
            EnterEvent.InputEnterEventBind(grid_load);

            //初始化数据显示结构
            initGrid();
            //初始化分页控件
            initGridPager()
            //加载数据
            grid_load(0, 20);
            getjquery("btnexport").bind("click", btnexport_click);
        });
        //初始化盘点清单回调
        function datachange_callback(data, status) {
            if (data.length > 0 && data[0].tcount > 0) {
                $.showInfoMsg(‘操作执行成功!‘);
                grid_load(0, 20);
            }
            else
                $.showErrorMsg(‘操作执行失败!‘);
            $.closeWaiting();
        }
        function btnexport_click() {

            var ph = new parmHelper();
            ph.Add("pagesize", 200000);
            var p = JSON2.stringify(ph.KeyValueArray);
            $.showWaiting();

            //window.openwindow("/FADB/ExportExcel?hook=839674039", "导出盘点数据", 500, 600);
            window.open("/FADB/ExportExcel?hook=839674039");
            $.closeWaiting();
        }
    </script>

</head>
<body class="easyui-layout">
    <div data-options="region:‘north‘,border:false,title:‘盘点数据查询‘" style="height: 135px;padding: 10px">
        <table class="grid" data-options="fit:true;">
            <tr>
                <td>单号:</td>
                <td>
                    <input class="easyui-combobox" id="ddlsnlist" name="ddlsnlist" data-options="valueField:‘sn‘,textField:‘sn‘" />
                </td>
                <td>资产编号:</td>
                <td><input class="text-left easyui-tooltip" type="text" title="请输入查询的资产编码." id="txtfano" name="name" /></td>
                <td>费用代码:</td>
                <td><input class="text-left easyui-tooltip" type="text" title="请输入查询的费用代码." id="txtcostcenter" name="name" /></td>
                <td>状态:</td>
                <td><input class="easyui-combobox" id="ddlstatuslist" name="ddlstatuslist" data-options="valueField:‘flag‘,textField:‘status‘" /></td>
            </tr>

            <tr>
                <td colspan="8">
                    <a href="#" id="btnsearch" class="easyui-linkbutton" title="" data-options="iconCls:‘icon-search‘">查 询</a><a href="#" id="btnexport" class="easyui-linkbutton" title="" data-options="iconCls:‘icon-save‘">导 出</a>
                </td>
            </tr>
        </table>
    </div>

    <div data-options="region:‘center‘,title:‘检索结果列表‘">
        <table id="dg" class="easyui-datagrid" style="width: 700px; height: 300px"></table>
    </div>
    <input type="hidden" id="hidids" />
</body>
</html>

  • 关键JS代码部分如红色背景部分所示
  • Controler代码示例

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FAMWebApp.Controllers
{
    public class FADBController : Controller
    {
        public FADBController()
        {
            _BaseControler = new BaseControler();
        }
        //
        // GET: /FADB/
        BaseControler _BaseControler;
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult GetDTJson()
        {
            return _BaseControler.GetDTJson(this.HttpContext);
        }
        public ActionResult GetTreeJson()
        {
            return _BaseControler.GetTreeJson(this.HttpContext);
        }
        public ActionResult GetTreeJson2()
        {
            return _BaseControler.GetTreeJson2(this.HttpContext);
        }
        public ActionResult GetDSJson()
        {
            return _BaseControler.GetDSJson(this.HttpContext);
        }
        /// <summary>
        /// 获取数据集JSon,含分页功能,easyui-datagrid 分页数据提供
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPagerDSJson()
        {
            return _BaseControler.GetPagerDSJson(this.HttpContext);
        }


        public ActionResult PostJson()
        {
            return _BaseControler.PostJson(this.HttpContext);
        }
      
  public ActionResult ExportExcel()
        {
            return _BaseControler.ExportExcel(this.HttpContext);
        }
    }
}

  • BaseControler ExportExcel实现

using DCL;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace FAMWebApp.Controllers
{
    public class BaseControler : Controller
    {
        int DBType { get { return (int)DataAccessControl.DBType.FAMS; } }
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult StartWorkFlow(HttpContextBase context)
        {
            string jsonstr = "";
            try
            {
                PN3.Workflow wf = new PN3.Workflow();
                Models.RequestProcessParmModels rpm = new Models.RequestProcessParmModels(context);
                List<Common.ProcessParms> list = rpm.ProcessParameterList;
                int index = 0;
                foreach (Common.ProcessParms item in list)
                {
                    try
                    {
                        wf.PNServer = "43.98.48.141";
                        wf.WorkFlowCode = item.ProcessName;             //工作流Code
                        wf.Parameters = item.Parms;                       //发起参数
                        wf.LockNo = item.SN;                   //申请单位号   
                        wf.AutoStartProcess();
                        index += 1;
                        rpm.SNS += item.SN + ",";
                    }
                    catch (Exception er)
                    {

                    }
                }
                try
                {
                    rpm.HookName = DataAccessControl.DBProviderInstance(DBType).GetStoreProcName(rpm.HookId);
                    rpm.ParmsDictionary["@sns"] = rpm.SNS;
                    rpm.ParmsDictionary["@userno"] = rpm.UserNo;
                    DataTable dt = DataAccessControl.DBProviderInstance(DBType).ExecStoreProcedureForGettingTable(rpm.ParmsDictionary, rpm.HookName);
                    jsonstr = Common.JsonHelper.DataTable2Json(dt);

                }
                catch { }
            }
            catch (Exception er)
            {
                jsonstr = "[{\"tcount\":\"0\",\"msg\":\"" + er.Message + "!\"}]";
            }

            return Content(jsonstr);
        }
        public ActionResult GetDTJson(HttpContextBase context)
        {
            Models.RequestParmModels rpms = new Models.RequestParmModels(context);
            rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
            DataTable dt = DataAccessControl.DBProviderInstance(DBType).ExecStoreProcedureForGettingTable(rpms.ParmsDictionary, rpms.HookName);
            string jsonstr = Common.JsonHelper.DataTable2Json(dt);
            return Content(jsonstr);
            //return Json(jsonstr, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetTreeJson(HttpContextBase context)
        {
            Models.RequestParmModels rpms = new Models.RequestParmModels(context);
            rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
           
            DataTable dt = DataAccessControl.DBProviderInstance(DBType).ExecStoreProcedureForGettingTable(rpms.ParmsDictionary, rpms.HookName);

            string jsonstr = Common.JsonHelper.DataTable2TreeJson("0", 0,rpms.AttributeFields, dt);
            return Content(jsonstr);
            //return Json(jsonstr, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetTreeJson2(HttpContextBase context)
        {
            //Models.RequestParmModels rpms = new Models.RequestParmModels(context);
            //rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
            Dictionary<string, object> dir = new Dictionary<string, object>();
            dir.Add("userno",""); //,
            List<string> list = new List<string>();
            list.Add("url");
            list.Add("orglevel");
            DataTable dt = DataAccessControl.DBProviderInstance(DBType).ExecStoreProcedureForGettingTable(dir, "fp_GetTreeDataSample");

            string jsonstr = Common.JsonHelper.DataTable2TreeJson("0", 0, list, dt);
            return Content(jsonstr);
            //return Json(jsonstr, JsonRequestBehavior.AllowGet);
        }
        public ActionResult GetDSJson(HttpContextBase context)
        {
            Models.RequestParmModels rpms = new Models.RequestParmModels(context);
            rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
            DataSet ds = DataAccessControl.DBProviderInstance(DBType).ExecStoredProcedure(rpms.ParmsDictionary, rpms.HookName);
            string jsonstr = Common.JsonHelper.DataSet2Json(ds);
            return Content(jsonstr);
        }
        /// <summary>
        /// 获取数据集JSon,含分页功能,easyui-datagrid 分页数据提供
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPagerDSJson(HttpContextBase context)
        {
            Models.RequestParmModels rpms = new Models.RequestParmModels(context);
            rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
            if (!rpms.ParmsDictionary.ContainsKey("@pageindex"))
            {
                rpms.ParmsDictionary["@pageindex"] = rpms.PageIndex;
            }
            if (!rpms.ParmsDictionary.ContainsKey("@pagesize"))
            {
                rpms.ParmsDictionary["@pagesize"] = rpms.PageSize;
            }
            DataSet ds = DataAccessControl.DBProviderInstance(DBType).ExecStoredProcedure(rpms.ParmsDictionary, rpms.HookName);
            string jsonstr = Common.JsonHelper.DataSet2JsonNew(ds);
            return Content(jsonstr);
        }


        public ActionResult PostJson(HttpContextBase context)
        {
            Models.RequestParmModels rpms = new Models.RequestParmModels(context);
            rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
            DataTable dt = DataAccessControl.DBProviderInstance(DBType).ExecStoreProcedureForGettingTable(rpms.ParmsDictionary, rpms.HookName);
            string jsonstr = Common.JsonHelper.DataTable2Json(dt);
            return Content(jsonstr);
            //return Json(jsonstr, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ExportExcel(HttpContextBase context)
        {
             Models.RequestExportFileParmModels rpms = new Models.RequestExportFileParmModels(context);
            rpms.HookName = DataAccessControl.DBProviderInstance((int)DataAccessControl.DBType.FAMS).GetStoreProcName(rpms.HookId);
            DataTable dt = DataAccessControl.DBProviderInstance(DBType).ExecStoreProcedureForGettingTable(rpms.ParmsDictionary, rpms.HookName);
            //Common.NPOIHelper npoi = new Common.NPOIHelper();
            //Common.NPOIHelper.ExportByWeb(context, dt, rpms.HeaderText, rpms.ExportFileName);
            //FileContentResult fr = new FileContentResult(Common.NPOIHelper.Export(dt, rpms.HeaderText).GetBuffer(), "application/ms-excel");
            //return fr;
            string filename = rpms.ExportFileName;
            if (null == filename || filename == "") filename = System.DateTime.Now.ToFileTime().ToString();
            return File(Common.NPOIHelper.Export(dt, rpms.HeaderText).GetBuffer(), "application/ms-excel", filename+".xls");
            //return Json(jsonstr, JsonRequestBehavior.AllowGet);
        }
    }
}

 

 

(四)Web应用开发---导出到Excel

标签:

原文地址:http://www.cnblogs.com/jeffry/p/5268365.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!