asp.net Mvc 导出Excel 用户自定义文件路径

前端Cshtml代码 


@{
    ViewBag.Title = "OrderChecking";
    Layout = "~/Views/Shared/_Form.cshtml";
}
<style>
    .topPanel .search .input-group .form-control {
        float: left;
        width: 100px;
        margin-left: 10px;
    }
</style>
<script>
    
    function btn_DownLoad() {

    //需要强制转成IE内核
        var filePath;
        try {
            var filePath;
            var objSrc = new ActiveXObject("Shell.Application").BrowseForFolder(0, '请选择保存路径', 0, '');
            if (objSrc != null) {
                filePath = objSrc.Items().Item().Path;
                if (filePath.charAt(0) == ':') {
                    alert('请选择文件夹.');
                    return;
                }
            }
        } catch (e) {
            alert(e + '请设置IE,单击 工具 菜单  -->  Internet选项  -->  安全  -->  自定义级别  -->  ActiveX  控件和插件:A.对标记为可安全执行脚本的ActiveX控件执行脚本*  -->  启用;B.对未标记为可安全执行脚本的ActiveX控件初始化并执行脚本  -->  启用;C.仅允许经过批准的域在未经提示的情况下使用 ActiveX  -->  启用;D.运行 ActiveX  控件和插件  -->  启用。,然后再尝试。');
            return;
        }


        $.submitForm({
            url: "/OrderManage/PurchaseSellOrder/DownLoadOrderCheckInfo?EndTime=" + $("#EndTime").val() + "&StartTime=" + $("#StartTime").val() + "&KeyWord=" + $("#txt_DeliverName").val() + "&OrderNo=" + $("#txt_Order").val() + "&filePath=" + filePath,
            success: function (returnInfo) {


                console.log(returnInfo);
            }
        });


    }




</script>


<form id="form1">
    <div class="topPanel">
        <div class="toolbar">
            <div class="btn-group">
                <a class="btn btn-primary" οnclick="$.reload()"><span class="glyphicon glyphicon-refresh"></span></a>
            </div>
            <script>$('.toolbar').authorizeButton()</script>
        </div>
        <div class="search">
            <table>
                <tr>
                    <td>
                        <div class="input-group">
                            <input id="txt_Order" type="text" class="form-control" placeholder="订单号" style="width: 200px;">
                            <input id="txt_DeliverName" type="text" class="form-control" placeholder="快递名/快递缩写" style="width: 200px;">
                            <input id="StartTime" name="StartTime" type="text" class="form-control input-wdatepicker" οnfοcus="WdatePicker()" placeholder="起始时间" />
                            <input id="EndTime" name="EndTime" type="text" class="form-control input-wdatepicker" οnfοcus="WdatePicker()" placeholder="结束时间" />
                            <a id="NF-DownLoad" class="btn btn-primary dropdown-text" οnclick="btn_DownLoad() "><i class="fa fa-pencil-square-o"></i>导出Excel</a>






                            <span class="input-group-btn">
                                <button id="btn_search" type="button" class="btn  btn-primary">
                                    <i class="fa fa-search"></i>
                                </button>
                            </span>
                        </div>
                    </td>
                </tr>
            </table>
        </div>
    </div>
    <div class="gridPanel">
        <table id="gridList"></table>
        <div id="gridPager"></div>
    </div>

</form>


后端

   /// <summary>
        /// 导出邮单信息
        /// </summary>
        /// <param name="StartTime"></param>
        /// <param name="EndTime"></param>
        /// <param name="KeyWord"></param>
        /// <param name="OrderNo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DownLoadOrderCheckInfo(string StartTime, string EndTime, string KeyWord, string OrderNo, string filePath)
        {
            filePath += @"\1.xls";
            string ApiF_UserId = “”;
            PurchaseOrderApp purchaseOrder_BLL = new PurchaseOrderApp();
            SellOrderApp sellOrder_BLL = new SellOrderApp();
            OrderDeliverApp orderDeliver_BLL = new OrderDeliverApp();
            try
            {
                DateTime DateStartTime = DateTime.Now.Date;
                DateTime DateEndTime = DateTime.Now.Date;


                if (!string.IsNullOrEmpty(StartTime))
                {
                    if (DateTime.TryParse(StartTime, out DateStartTime) == false)
                        return Error("开始时间不正确,请输入正确的时间");
                }
                if (!string.IsNullOrEmpty(EndTime))
                {
                    if (DateTime.TryParse(EndTime, out DateEndTime) == false)
                        return Error("结束时间不正确,请输入正确的时间");
                }
                if (DateStartTime > DateEndTime)
                    return Error("开始时间不能大于结束时间,请输入正确的时间");


                var data = orderCheckingApp.GetListOrderChecking_DownLoad(StartTime, EndTime, KeyWord, OrderNo, ApiF_UserId);  //数据源 自己修改 list类型


                DataTable dt = ToDataTable(data);    //list转换成datatable


                NPOIExcel Ex = new NPOIExcel();
                if (Ex.ToExcel(dt, "邮单信息", "Data", filePath))
                    return Success("恭喜,导出Excel成功!");
                else
                    return Error("导出Excel失败!");


            }
            catch (Exception)
            {
                throw;
            }
        }


        /// <summary>
        /// List 转换成Table
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        /// <returns></returns>
        private DataTable ToDataTable<T>(List<T> items)
        {
            var tb = new DataTable(typeof(T).Name);


            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);


            foreach (PropertyInfo prop in props)
            {
                Type t = GetCoreType(prop.PropertyType);
                tb.Columns.Add(prop.Name, t);
            }


            foreach (T item in items)
            {
                var values = new object[props.Length];


                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }


                tb.Rows.Add(values);
            }


            return tb;
        }




        /// <summary>
        /// Return underlying type if type is Nullable otherwise return the type
        /// </summary>
        public static Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }


        /// <summary>
        /// Determine of specified type is nullable
        /// </summary>
        public static bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }
        #endregion



 /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public bool ToExcel(DataTable table)
        {
            FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            IWorkbook workBook = new HSSFWorkbook();
            this._sheetName = this._sheetName.IsEmpty() ? "sheet1" : this._sheetName;
            ISheet sheet = workBook.CreateSheet(this._sheetName);


            //处理表格标题
            IRow row = sheet.CreateRow(0);
            row.CreateCell(0).SetCellValue(this._title);
            sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1));
            row.Height = 500;


            ICellStyle cellStyle = workBook.CreateCellStyle();
            IFont font = workBook.CreateFont();
            font.FontName = "微软雅黑";
            font.FontHeightInPoints = 17;
            cellStyle.SetFont(font);
            cellStyle.VerticalAlignment = VerticalAlignment.Center;
            cellStyle.Alignment = HorizontalAlignment.Center;
            row.Cells[0].CellStyle = cellStyle;


            //处理表格列头
            row = sheet.CreateRow(1);
            for (int i = 0; i < table.Columns.Count; i++)
            {
                row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName);
                row.Height = 350;
                sheet.AutoSizeColumn(i);
            }


            //处理数据内容
            for (int i = 0; i < table.Rows.Count; i++)
            {
                row = sheet.CreateRow(2 + i);
                row.Height = 250;
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString());
                    sheet.SetColumnWidth(j, 256 * 15);
                }
            }


            //写入数据流
            workBook.Write(fs);
            fs.Flush();
            fs.Close();


            return true;
        }


        /// <summary>
        /// 导出到Excel
        /// </summary>
        /// <param name="table"></param>
        /// <param name="title"></param>
        /// <param name="sheetName"></param>
        /// <returns></returns>
        public bool ToExcel(DataTable table, string title, string sheetName, string filePath)
        {
            this._title = title;
            this._sheetName = sheetName;
            this._filePath = filePath;
            return ToExcel(table);
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

pandi18

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值