Easy UI 上传Excel 后台上传根目录并读取数据

前台运用EasyUI FileBox 控件 前台想用此空间 EasyUI 版本需1.4以上,本人用1.5.2

<div id="Excel" class="easyui-dialog" buttons="#dlg-buttons" iconcls="icon icon-edit" closed="true" modal="true" title="导入窗口" style="width: 600px;
        height: 300px; padding: 5px">
         <div  id="tb" style="padding:5px;height:70px">
        <!-------------------------------搜索框----------------------------------->
            <fieldset>
                <legend>Excel导入操作</legend>
                <form id="ffSearch" method="post" enctype="multipart/form-data">
                    <div title="Excel导入操作" style="padding: 5px" data-options="iconCls:'icon-key'">
                        <input class="easyui-validatebox" type="hidden" id="AttachGUID" name="AttachGUID" />
                        <br />
                        <input class="easyui-filebox" id="file_upload" style="width:300px" />
                    </div>
                </form>
                <div id="div_files"></div>
            </fieldset>
                
        <!-------------------------------详细信息展示表格----------------------------------->
        <!--<table id="grid" title="用户操作" data-options="iconCls:'icon-view'">            
        </table>-->
    </div>
       </div>

JAVAscript中把路径传到后台

 //上传文件操作
        function UploadFile(_obj, file_ctrlname, guid_ctrlname, div_files) {
            var value = $("#" + file_ctrlname).filebox('getValue');
            var files = $("#" + file_ctrlname).next().find('input[type=file]')[0].files;
            //console.log(files);

            //传入this参数,也可以用这个获取文件
            //var files = $(_obj).context.ownerDocument.activeElement.files;
            //console.log(files);
   
            console.log(value)
            var guid = $("#" + guid_ctrlname).val();
            
            if (value && files[0]) {
                //构建一个FormData存储复杂对象
                var formData = new FormData();
                formData.append("folder", '数据导入文件');
                formData.append("guid", guid);
                formData.append('Filedata', files[0]); //默认的文件数据名为“Filedata”

                $.ajax({
                    url: '../ashx/EQ/UPMMonthMaintainPlanHandler.ashx?action=query&value=' + value, //单文件上传
                    type: 'POST',
                    processData: false,
                    contentType: false,
                    data: formData,
                    success: function (json) {
                        search1();
                        $('#Excel').dialog('close');
                        if (json) {

                            $.show_warning_inframe("文件已上传,数据加载完毕!", "info");
                        }
                        else {
                            $.show_warning_inframe("上传的Excel文件检查不通过。请根据页面右上角的Excel模板格式进行数据录入。", "info");
                        }
                    },
                    error: function (xhr, status, error) {
                        $.show_warning_inframe("提示", "操作失败", "info"); //xhr.responseText
                    }
                });
            }

        }

通过前台传来路径在上传网站目录下,通过行和列来得到文件里面数据
后台引用Microsoft.Office.Interop.Excel、System.Web来解析

 public void query(HttpContext context) {
            //MIMPlatFormNFCA.DalSqlserver.aExcelDAL Excel = new MIMPlatFormNFCA.DalSqlserver.aExcelDAL();
            //MIMPlatFormNFCA.DalSqlserver.aExcelDAL excelWrite = MIMPlatFormNFCA.DalSqlserver.aExcelDAL.CreateExcelHelper();
            //excelWrite.CreateExcel(@"C:\MyWorks\test.xlsx");
            //excelWrite.SelectPage(1);
            //excelWrite.WriteGrid(1, 1, "test11");
            //excelWrite.WriteGrid(1, 2, "test12");
            //excelWrite.WriteGrid(2, 1, "test21");
            //excelWrite.WriteGrid(2, 2, "test22");
            //excelWrite.Save();
            //excelWrite.Close();
              //获取客户端上传的文件集合
                HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
                //判断是否存在文件
                string path = "";
                if (files.Count > 0)
                {
                    //获取文件集合中的第一个文件(每次只上传一个文件)
                    HttpPostedFile file = files[0];
                    //定义文件存放的目标路径
                    string targetDir = System.Web.HttpContext.Current.Server.MapPath("~/FileUpLoad/Product");
                    //创建目标路径
                    System.IO.Directory.CreateDirectory(targetDir);
                    //组合成文件的完整路径
                    path = System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file.FileName));
                    //保存上传的文件到指定路径中
                    file.SaveAs(path);
                }
                else { 
                path = "";
                }
            string value = PublicMethod.GetString("value");
            MIMPlatFormNFCA.DalSqlserver.aExcelDAL excelRead = MIMPlatFormNFCA.DalSqlserver.aExcelDAL.CreateExcelHelper();
            excelRead.OpenExcel(@""+path+"");
           
            excelRead.SelectPage(1);
            int count = excelRead.RowCount;
            MIMPlatFormNFCA.Model.MonthMaintainPlan model = null;
            model = new MIMPlatFormNFCA.Model.MonthMaintainPlan();
            bool isSuccess = false;
            for (int i = 1; i < count; i++)
            {
                DateTime date = DateTime.Parse(excelRead.ReadGrid(i + 1, 1).ToString());
                string datey = date.ToString("yyyy-MM-dd");
                DateTime dateE = DateTime.Parse(datey);
                string sbbm = excelRead.ReadGrid(i + 1, 2);
                string yxxss = excelRead.ReadGrid(i + 1, 3);
                string bylb = excelRead.ReadGrid(i + 1, 4);
                string jhkssj = excelRead.ReadGrid(i + 1, 5);
                string planWBtime = excelRead.ReadGrid(i + 1, 7);
                string jihuaEHour = Regex.Match(planWBtime, "\\d+").Value;
                string jihuaSHour = jhkssj.Split(':')[0].ToString();
                int hour = Convert.ToInt32(jihuaSHour) + Convert.ToInt32(jihuaEHour);
                string endTime = hour + ":00";
                setModel(ref model, false, dateE, sbbm, yxxss, bylb, jhkssj, endTime, planWBtime);
                isSuccess = bllMonthMaintainPlan.Insert(model,UserID, UserIP, WebPage);
            }
            excelRead.Close();
            context.Response.Write(jsonResult.setMsg(isSuccess, bllMonthMaintainPlan.Message).getJsonString());
        }

后台第二种方法 将数据转为DateTable

 private void upload(HttpContext context)
        {
            bool isSuccess = false;
            HttpFileCollection files = HttpContext.Current.Request.Files;//获取客户端上传的文件集合
            string path = "";
            string fileType = "";
            if (files.Count > 0)//判断是否存在文件
            {
                HttpPostedFile file = files[0];//获取文件集合中的第一个文件(每次只上传一个文件)
                string targetDir = HttpContext.Current.Server.MapPath("~/FileUpLoad/Product");//定义文件存放的目标路径
                Directory.CreateDirectory(targetDir);//创建目标路径
                string oldFileName = Path.GetFileName(file.FileName);//获取原文件名
                fileType = oldFileName.Substring(oldFileName.LastIndexOf('.') + 1);//获取原文件类型
                string newFileName = "维修台账" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "." + fileType;//组合新文件名加类型
                path = Path.Combine(targetDir, newFileName);//组合成文件的完整路径
                file.SaveAs(path);//保存上传的文件到指定路径中
            }
            if (path != "")
            {
                string connOleDBStr = "";
                DataSet ds = new DataSet();
                if (fileType == "xls")
                {
                    connOleDBStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1';"; // Office 07及以下版本
                }
                else if (fileType == "xlsx")
                {
                    connOleDBStr = "Provider=Microsoft.Ace.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 12.0;HDR=NO;IMEX=1';"; //Office 07以上版本 
                }
                if (connOleDBStr != "")
                {
                    using (OleDbConnection conn = new OleDbConnection(connOleDBStr))
                    {
                        conn.Open();
                        DataTable dtExcel = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
                        string firstSheetName = dtExcel.Rows[0][2].ToString();
                        string sql = string.Format("select * from [{0}]", firstSheetName);
                        OleDbDataAdapter odda = new OleDbDataAdapter(sql, connOleDBStr);
                        odda.Fill(ds);
                        conn.Close();
                        conn.Dispose();
                        DataTable dt = ds.Tables[0];
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值