Import data efficiently

 

protected void Button1_Click(object sender, EventArgs e)

        {
            if (FileUpload1.HasFile == false)//HasFile is used to check whether FileUpload has a specified file
            {
                Response.Write("<script>alert('Please select an Excel file')</script> ");
                return;/ / When there is no file, return
            }
            string IsXls = System.IO.Path.GetExtension(FileUpload1.FileName).ToString().ToLower();//System.IO.Path.GetExtension to get the extension of the file
            if (IsXls ! = ".xlsx")
            {
                Response.Write("<script>alert('Only Excel file can be selected')</script>");
                return;//When the selected file is not Excel, return
            }
            string filename = FileUpload1 .FileName; //Get Execle file name DateTime date function
            string savePath = Server.MapPath(("/upfiles\\") + filename);//Server.MapPath obtains the relative path of the virtual server
            FileUpload1.SaveAs(savePath); //SaveAs saves the uploaded file content on the server
            DataSet ds = ExcelSqlConnection(savePath, filename); //Call the custom method
            DataRow[] dr = ds.Tables[0].Select(); //Define a DataRow array
            int rowsnum = ds.Tables[0].Rows.Count;
            if (rowsnum == 0)
            {
                Response.Write("<script>alert('The Excel table is empty, no data!')</script>"); //When the Excel table is empty, prompt the user
            }
            else
            {
                //for (int i = 0; i < dr.Length; i++)
                //{
                    //Except you need to create an "upfiles" folder, you don't need to worry about other things, you only need to get the Excel values ​​in the following way, and then insert these values ​​into the database in your way
                    //string title = dr[i]["name"].ToString();
                    //string linkurl = dr[i]["job number"].ToString();
                    //string categoryname = dr[i][" Gender"].ToString();
                    //string customername = dr[i]["Birthdate"].ToString();




                    //string str = ConfigurationManager.AppSettings["ConnectionString"];       
                    //Declare database connection
                SqlConnection conn = new SqlConnection("connection string");


                    conn.Open();
                    //declare SqlBulkCopy, using to release unmanaged resources
                    using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
                    {
                        //The amount of data inserted in a batch
                        sqlBC.BatchSize = 1000;
                        //The number of seconds allowed for the operation to complete before the timeout, if the transaction times out, the transaction will not be committed, and the data will be returned Roll, all copied rows will be removed from the target table
                        sqlBC.BulkCopyTimeout = 60;


                        //Set the NotifyAfter property to call the corresponding event every time 10000 pieces of data are inserted.  
                        sqlBC.NotifyAfter = 10000;
                        sqlBC.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);


                        //Set the table to be written in batches
                        sqlBC.DestinationTableName = "location";
                        //locationID Subwaystation Subwaydistance Busstation Busline SurroundingEstate state EditUser EditDate


                        //The custom datatable corresponds to the fields of the database 
                        sqlBC.ColumnMappings.Add("City", "CityId");
                        sqlBC.ColumnMappings.Add("Administrative District", "Area");
                        sqlBC .ColumnMappings.Add("Property name", "Estate");
                        sqlBC.ColumnMappings.Add("Eastfacing", "Eastfacing");
                        sqlBC.ColumnMappings.Add("South facing", "Southfacing");
                        sqlBC.ColumnMappings .Add("West facing", "Westfacing");
                        sqlBC.ColumnMappings.Add("North facing", "Northfacing");
                        sqlBC.ColumnMappings.Add("Supermarket", "Supermarket");
                        sqlBC.ColumnMappings.Add("Meat Market", "market");
                        sqlBC.ColumnMappings.Add("Hospital", "Hospital");
                        sqlBC.ColumnMappings .Add("Bank", "Bank");
                        sqlBC.ColumnMappings.Add("School", "School");
                        sqlBC.ColumnMappings.Add("Park", "Park");
                        sqlBC.ColumnMappings.Add("Subway line", "metro");
                        sqlBC.ColumnMappings.Add("Subwaystation", "Subwaystation");
                        sqlBC.ColumnMappings. Add("Time to subway station", "Subwaydistance");
                        sqlBC.ColumnMappings.Add("Bus Station", "Busstation");
                        sqlBC.ColumnMappings.Add("Bus Line", "Busline");
                        sqlBC.ColumnMappings.Add("Surrounding Estate", "SurroundingEstate");
                       


                        //sqlBC.ColumnMappings.Add("Name", "name");
                        / /sqlBC.ColumnMappings.Add("age", "age");
                        sqlBC.WriteToServer(dr);
                        //Response.Write("<script>alert('Import content:" + ex.Message + "')</ script>");
                    //}
                        //Response.Write("<script>alert('Excle table imported successfully!');</script>");
                        Response.Write("<scpript>alert(' Excle table import " + rowsnum + "!';</script>");
                }
               
            }
        }


        public static DataSet ExcelSqlConnection(string filepath, string tableName)
        {
            //string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1'";


            string strCon = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=Yes;IMEX=1;'", filepath);
            OleDbConnection ExcelConn = new OleDbConnection(strCon);
            try
            {
                //string strCom = string.Format("SELECT * FROM [Sheet1$]");
                string strCom = string.Format("SELECT * FROM [人工整理$]");
                ExcelConn.Open();
                OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, ExcelConn);
                DataSet ds = new DataSet();
                myCommand.Fill(ds, "[" + tableName + "$]");
                ExcelConn.Close();
                return ds;
            }
            catch
            {
                ExcelConn.Close();
                return null;
            }
        }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324935468&siteId=291194637