Upload the Excel file, use OLEDB to connect and read the data, the "microsoft.ACE.oledb.12.0" is not registered on the local computer

Preface

Recently, there is a need to upload and import an Excel file in the project to obtain the information in the file, and save it in the database according to the needs of the business and the processing of some data. Let me introduce how I did it.

Ideas

(1) There is a file upload button on the front page (if you want a nice button, you can set your own style, or use the button of layUI)
(2) Use the FormData() object in JS to append the file to be uploaded to append() Go in. Use AJAX to call the interface, and use HttpPostedFile to receive at the back end, which is Request.Files[0]
(3) After obtaining the file uploaded by the client, this place can perform some verification processing of the file, such as verification of some file types Whether it is an image file, excel file, etc. After no problem upload it to a local file, if you are using the HttpPostedFile object, you can directly call one of his save methods SaveAs ("save path")
(4) After the file is uploaded, use the OleDb object to read it. While reading, you can fetch and save to the database on demand.

Implementation

JavaScript code

       //点击上传Excel事件,我这里使用的是Layui的上传文件按钮,所以事件也是使用的是它的格式。
             upload.render({
    
    
                elem: '#btn_Excel'
                , url: '/'
                , auto: false
                , acceptMime: ".xlsx,.xls"
                , before: function (obj) {
    
    }
                , type: "file"
                , accept: 'file' //普通文件
                , choose: function (obj) {
    
    
                    var files = obj.pushFile();
                    obj.preview(function (index, file, result) {
    
    
                        var formData = new FormData();
                        //这里这个file就是我们选择好了的文件对象
                        //将它追加在FormData对象中
                        formData.append("file", file);
                        $.ajax({
    
    
                            url: "/后端接口",//填写你自己的后端接口
                            type: 'POST',
                            data: formData,
                            // 告诉jQuery不要去处理发送的数据
                            processData: false,
                            // 告诉jQuery不要去设置Content-Type请求头
                            contentType: false,
                            beforeSend: function () {
    
    
                                layui.use('layer', function () {
    
    
                                    layerloadindex = layer.load(1, {
    
    
                                        shade: [0.1, '#fff'] //0.1透明度的白色背景
                                        , content: '文件上传中...请稍候...',
                                        success: function (layero) {
    
    
                                            layero.find('.layui-layer-content').css({
    
    
                                                'padding-top': '39px',
                                                'width': '180px'
                                            });
                                        }
                                    });
                                });  
                            
                            },
                            success: function (data) {
    
    
                                if (data == "true") {
    
    
                                    //关闭 加载动画
                                    layer.close(layerloadindex);
                                    //给出提示
                                    layer.msg('文件上传成功!!');
                                } else {
    
     layer.msg(data); }
                            },
                            error: function (data) {
    
    
                                layer.close(layerloadindex);
                                layer.msg(data);
                            }
                        });
                    });
                }
                , done: function (res) {
    
    }
                , error: function () {
    
    }
            });

Back-end code (I use general processing files here)

   /// <summary>
        /// Excel文件读取
        /// </summary>
        /// <param name="Postfile"></param>
        /// <param name="cDate"></param>
        /// <returns></returns>
        private string RdIn_upload_keep(HttpPostedFile Postfile, string cDate)
        {
    
    
            //对文件日期进行检查
            cDate = dyTools.checkTools.CheckDateFormation(cDate);
            if (cDate == "") cDate = DateTime.Now.ToString("yyyy-MM-dd");
            //【这里可以执行,上传是否重复可以考虑对数据库进行覆盖即是对表的删除】
            //这里是将时间转化成年月模式,比如2020-10-01  处理之后就是2020-10
            cDate = cDate.Split('-')[0] +'-'+ cDate.Split('-')[1];
            //将存取Excel的虚拟路径映射为物理路径
                string cPath = HttpContext.Current.Request.MapPath("/Content/excel");
            //获取文件名字
            string cFileName = Path.GetFileName(Postfile.FileName);
            //获取文件的扩展名
            string cFileExt = Path.GetExtension(cFileName);
            if (cFileExt != ".xlsx") return "Excel文件不正确";
            //生成一个新文件名称
            string cNewFileName = Guid.NewGuid().ToString();
            cNewFileName = cPath + "\\" + cNewFileName + cFileExt;
            Postfile.SaveAs(cNewFileName);
        

Then this place is already saving the Excel file, then all that needs to be done is to use the OLEDB object connection to read.
(1) First import the namespace using System.Data.OleDb;
after the import is complete, then you can proceed.

Note that it is the code immediately following the above method.

            OleDbConnection dbOle = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + cNewFileName + ";Extended Properties='Excel 12.0;HDR=Yes;IMEX=1;'");
            try {
    
     dbOle.Open(); }
            catch{
    
    return "不能打开EXCEL文件";}
            OleDbCommand dbOleCommand = dbOle.CreateCommand();
            string cSheet = "Sheet1";

OleDbConnection data source connection object (inside the parameter is the connection string) this place should pay attention to, different file suffixes, the connection string is different
For example:

Xlsx file

(1) The following is the syntax format:
Provider= Microsoft.ACE.OLEDB.12.0; Data Source= Uploaded file address; Extended Properties= "Excel 12.0 Xml;HDR=YES;IMEX=1";

Xlsb file

(2) The following is the syntax format:
Provider= Microsoft.ACE.OLEDB.12.0; Data Source= Uploaded file address; Extended Properties= "Excel 12.0;HDR=YES";";

Xlsm file

(3) The following is the grammatical format:
Provider= Microsoft.ACE.OLEDB.12.0; Data Source= Uploaded file address; Extended Properties= "Excel 12.0 Macro;HDR=YES";;

So what we need here is the Xlsx file, and the connection string used is the first one. At the same time, we only need to treat Excel as a database, so it's easy to read the table.

For example, we now read the data

  OleDbCommand dbOleCommand = dbOle.CreateCommand();
  string cSheet = "Sheet1";
  dbOleCommand.CommandText = "SELECT * FROM [" + cSheet + "$]";
  OleDbDataReader dbOleRec =  dbOleCommand.ExecuteReader();

Just read it in this way. There is a CommandText property and an ExecuteReader() object. Even the SQL statement is almost the same. Then my string cSheet = "Sheet1"; Why is Sheet1? Then everyone needs to decide according to their own situation.
Insert picture description here

Now that ExecuteReader has come out, I think everyone knows what to do.

 if (dbOleRec.HasRows)
            {
    
    
                while (dbOleRec.Read())
                {
    
    
                  //就在这个地方读取就好了
               
                }
           }

Note: When reading, press the index instead of A, B, C, D...AA in Excel. dbOleRec[0].ToString(). Then you can process the data according to your own business needs, or save it to the database.
Come to this step, then you will encounter some problems.

"Microsoft.ACE.oledb.12.0" is not registered on the local computer
Insert picture description here

Have you seen it, comrades, I also fell into this pit, and I have been looking for a solution for a long time. Hahaha it's okay, let me recommend his solution to everyone, I just used his method and finally solved it! The "microsoft.ACE.oledb.12.0 solution" is not registered on the local computer

At last

That's it for today's sharing. If you have any questions, of course you can leave a message below. Please correct me. Learn together and make progress together

Guess you like

Origin blog.csdn.net/WenRouDG/article/details/108961699