.NET利用AccessDatabaseEngine作为辅助工具实现导入EXECL表数据

采用这种方式,只需要新建一个页面做为辅助导入页面,实现的原理是将EXECL表上传到服务器,然后通过程序将EXECL表转化到AccessDatabase数据暂存,然后转化为DataTable数据,这样你就可以根据自己的要求存储数据;

首先,需要安装一个AccessDatabaseEngine.exe文件;

前端页面代码:

    <div class="setting-page-dialog">
            <table class="table table-config">
                <tr>
                    <th>
                        <span class="required">*span>导入文档:
                    th>
                    <td>
                         <input type="file" class='action-item' runat="server" ID="txtFile"/>
                    td>
                tr>
                <tr>
                    <td colspan="2">
                        <span class="d_default"> 注意:文档格式:Excel,文档最大5M,最多500条会员数据。a>                                          
                    td>
                tr>
            table>
        div>
        <div class="footer-fixed">
             <asp:Button ID="SaverButProductNotify" runat="server" Text="导入会员" class="btn" OnClick="LBtnUpProducts_Click" />          
        div>  

后端代码如下:

       //上传按钮触发事件
       protected void LBtnUpProducts_Click(object sender, EventArgs e)
        {
            //上传文件
            string url = UpLoadXls(txtFile);
            if (string.IsNullOrEmpty(url))
                return;
            //获取上传文件数据
            var  dtUsers=  ImpExcelDt(url);

            if (dtUsers != null)
            {
                //将数据添加到指定的数据库(这里根据自己实际需求来保存上传的数据)
                AddUser(dtUsers);//代码(略)
            }
        }
        /// 
        /// 上传Excel文件
        /// 
        /// 上传的控件名
        /// 
        private string UpLoadXls(System.Web.UI.HtmlControls.HtmlInputFile inputfile)
        {
            string orifilename = string.Empty;
            string uploadfilepath = string.Empty;
            string modifyfilename = string.Empty;
            string fileExtend = "";//文件扩展名
            int fileSize = 0;//文件大小
            try
            {
                if (inputfile.Value != string.Empty)
                {
                    //得到文件的大小
                    fileSize = inputfile.PostedFile.ContentLength;
                    if (fileSize == 0)
                    {
                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "");
                        return null;
                        //throw new Exception("导入的Excel文件大小为0,请检查是否正确!");
                    }
                    //获取文件的大小
                    if (fileSize > 1024*1024*5)
                    {
                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "");
                        return null;
                    }
                    //得到扩展名
                    fileExtend = inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
                    //if (inputfile.PostedFile.ContentType != "application/vnd.ms-excel")
                    if (!(fileExtend.ToLower() == "xls" || fileExtend.ToLower() == "xlsx"))
                    {
                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "");
                        return null;
                        //throw new Exception("你选择的文件格式不正确,只能导入EXCEL文件!");
                    }

                    //路径
                    uploadfilepath = Server.MapPath("/uploads/upexcelusers");
                    //新文件名
                    modifyfilename = System.Guid.NewGuid().ToString();
                    modifyfilename += "." + inputfile.Value.Substring(inputfile.Value.LastIndexOf(".") + 1);
                    //判断是否有该目录
                    System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(uploadfilepath);
                    if (!dir.Exists)
                    {
                        dir.Create();
                    }
                    orifilename = uploadfilepath + "\\" + modifyfilename;
                    //如果存在,删除文件
                    if (File.Exists(orifilename))
                    {
                        File.Delete(orifilename);
                    }
                    // 上传文件(保存)
                    inputfile.PostedFile.SaveAs(orifilename);
                }
                else
                {
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "");
                    return null;
                }
            }
            catch (Exception ex)
            {
                //创建日志操作实例
                ILog log = LogHelper.GetLogger();
                //为日志参数赋值
                log.Caption = "上传Excel报错";
                log.SQL.Append(ex.ToString());
                log.Content.AppendNewLine(ex.ToString());
                //写日志
                log.WriteTraceLog(ex);

                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok", "");

                return null;
            }
            return orifilename;
        }
        /// 
        /// 从Excel导入帐户(新建oleDb连接,Excel整表读取,适于无合并单元格时)
        /// 
        /// 完整路径名
        /// 
        private DataTable ImpExcelDt(string fileName)
        {
            OleDbConnection oleDBConn = null;
            OleDbDataAdapter oleAdMaster = null;
            try
            {
                //Provider=Microsoft.Jet.OLEDB.4.0;Data Source=winpy.mdb;Persist Security Info=True
                //访问地址
                string oleDBConnString = String.Empty;
                //oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
                oleDBConnString = "Provider=Microsoft.ACE.OLEDB.12.0;"; 
                oleDBConnString += "Data Source=";
                oleDBConnString += fileName;
                //oleDBConnString += ";Persist Security Info=True;";
                oleDBConnString += ";Extended Properties='Excel 8.0;HDR=Yes;imex=1';";

                DataTable m_tableName = new DataTable();
                DataSet ds = new DataSet();
                //创建访问对象
                oleDBConn = new OleDbConnection(oleDBConnString);
                oleDBConn.Open();
                //获取访问的数据
                m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                //解析获取的数据
                if (m_tableName != null && m_tableName.Rows.Count > 0)
                {
                    m_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString();

                    string sqlMaster = " SELECT *  FROM [" + m_tableName.TableName + "]";
                    oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
                    oleAdMaster.Fill(ds, "m_tableName");
                    oleAdMaster.Dispose();
                }

                oleDBConn.Close();
                oleDBConn.Dispose();

                if (ds.Tables.Count > 0)
                    return ds.Tables[0];
                else
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok",
                        "");
            }
            catch (Exception ex)
            {
                if (oleAdMaster != null)
                    oleAdMaster.Dispose();
                if (oleAdMaster != null)
                {
                    if (oleDBConn.State == ConnectionState.Open)
                        oleDBConn.Close();

                    oleDBConn.Dispose();
                }

                //创建日志操作实例
                ILog log = LogHelper.GetLogger();
                //为日志参数赋值
                log.Caption = "导入Excel数据报错";
                log.SQL.Append(ex.ToString());
                log.Content.AppendNewLine(ex.ToString());
                //写日志
                log.WriteTraceLog(ex);

                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "ok",
                    "");
            }
            return null;
        }

使用这种方式可以便于数据导入到数据库保持一致性,提高导入的效率,简单方便使用
下载文件路径:https://pan.baidu.com/s/1miG73Mo

你可能感兴趣的:(.NET学习)