无法从system.data.common.dbconnection转换为system.data,sqlconnection

时间:2019-05-09 15:04:05

标签: c# asp.net-mvc-5 entity-framework-6 epplus sqlbulkcopy

我正在将数据从excel文件导入到sql数据库。我正在使用MVC 5和实体框架6。我正在使用epplus导入数据,并使用sqlbulkcopy将数据导入sql。 我收到3个错误: 1)excelImportDBEntities.Database.Connection 2)sqlbulkcopy是一个名称空间,但用作类型 3)ObjectReader

public async System.Threading.Tasks.Task<ActionResult> 
ApplicationAsync(FormCollection formCollection)
    {
        var usersList = new List<bomApplicationImportTgt>();
        if (Request != null)
        {
            HttpPostedFileBase file = Request.Files["UploadedFile"];
            if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
            {
                string fileName = file.FileName;
                string fileContentType = file.ContentType;
                byte[] fileBytes = new byte[file.ContentLength];
                var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
                using (var package = new ExcelPackage(file.InputStream))
                {
                    var currentSheet = package.Workbook.Worksheets;
                    var workSheet = currentSheet.First();
                    var noOfCol = workSheet.Dimension.End.Column;
                    var noOfRow = workSheet.Dimension.End.Row;
                    for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
                    {
                        var user = new bomApplicationImportTgt();
                        user.date = Convert.ToDateTime(workSheet.Cells[rowIterator, 1].Value);
                        user.Description = workSheet.Cells[rowIterator, 2].Value?.ToString();
                        user.SequenceNumber = Convert.ToInt32(workSheet.Cells[rowIterator, 3].Value);
                        user.PartNumber = workSheet.Cells[rowIterator, 4].Value?.ToString();
                        user.PartsName = workSheet.Cells[rowIterator, 5].Value?.ToString();
                        user.SP = workSheet.Cells[rowIterator, 6].Value?.ToString();
                        user.INT = workSheet.Cells[rowIterator, 7].Value?.ToString();
                        user.SN = workSheet.Cells[rowIterator, 8].Value?.ToString();
                        user.SZ = workSheet.Cells[rowIterator, 9].Value?.ToString();
                        user.C = workSheet.Cells[rowIterator, 10].Value?.ToString();
                        user.E_F = workSheet.Cells[rowIterator, 11].Value?.ToString();
                        user.Block = workSheet.Cells[rowIterator, 12].Value?.ToString();
                        user.SEC = workSheet.Cells[rowIterator, 13].Value?.ToString();
                        user.Item = workSheet.Cells[rowIterator, 14].Value?.ToString();
                        user.SUF = workSheet.Cells[rowIterator, 15].Value?.ToString();
                        user.Model = workSheet.Cells[rowIterator, 16].Value?.ToString();
                        user.M_E_F = workSheet.Cells[rowIterator, 17].Value?.ToString();
                        user.OP = workSheet.Cells[rowIterator, 18].Value?.ToString();
                        user.Type = workSheet.Cells[rowIterator, 19].Value?.ToString();
                        user.Quantity = workSheet.Cells[rowIterator, 20].Value?.ToString();
                        user.PLGRPCD = workSheet.Cells[rowIterator, 21].Value?.ToString();
                        user.PL1 = workSheet.Cells[rowIterator, 22].Value?.ToString();
                        user.ATC1 = workSheet.Cells[rowIterator, 23].Value?.ToString();
                        user.PL2 = workSheet.Cells[rowIterator, 24].Value?.ToString();
                        user.ATC2 = workSheet.Cells[rowIterator, 25].Value?.ToString();
                        user.PL3 = workSheet.Cells[rowIterator, 26].Value?.ToString();
                        user.ATC3 = workSheet.Cells[rowIterator, 27].Value?.ToString();
                        user.Plant = workSheet.Cells[rowIterator, 28].Value?.ToString();
                        user.SHR = workSheet.Cells[rowIterator, 29].Value?.ToString();
                        user.DC_Number = workSheet.Cells[rowIterator, 30].Value?.ToString();
                        user.FileName = fileName;
                        usersList.Add(user);
                    }
                }
            }
        }
        using (Dev_Purchasing_New_ModelEntities excelImportDBEntities = new Dev_Purchasing_New_ModelEntities())
        {
            await new BulkWriter().InsertAsync(usersList, "bomApplicationImportTgt", excelImportDBEntities.Database.Connection, CancellationToken.None);
        }
        return View("Application");
    }

我试图使导入更快,这就是为什么我使用sqlbulkcopy的原因,但是由于这些错误,我无法这样做。

1 个答案:

答案 0 :(得分:0)

请检查以下代码将excel上载到SQL批量上载

控制器代码

    [HttpPost]
    public ActionResult ImportExcel(HttpPostedFileBase postedFile)
     {
      try
        {
          string filePath = string.Empty;
          if (postedFile != null)
          {
            //Save File
            string path = Server.MapPath("~/ExcelUpload/");
            if (!Directory.Exists(path))
            {
               Directory.CreateDirectory(path);
            }
            filePath = path + Path.GetFileName(postedFile.FileName);
            string extension = Path.GetExtension(postedFile.FileName);
            postedFile.SaveAs(filePath);
            //End
            string conString = string.Empty;
            switch (extension)
            {
             case ".xls": //Excel 97-03.
                  conString = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                  break;
             case ".xlsx": //Excel 07 and above.
                  conString = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                break;
            }
            //Add Excel Data To Datatable
            DataTable dt = new DataTable();               
            conString = string.Format(conString, filePath);
            //Get Actual Data for Excel
            using (OleDbConnection connExcel = new OleDbConnection(conString))
            {
               using (OleDbCommand cmdExcel = new OleDbCommand())
               {
                  using (OleDbDataAdapter odaExcel = new OleDbDataAdapter())
                   {
                     cmdExcel.Connection = connExcel;
                     //Get the name of First Sheet.
                     connExcel.Open();
                     DataTable dtExcelSchema;
                     dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                     string sheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
                     connExcel.Close();
                     //Read Data from First Sheet.
                     connExcel.Open();
                     cmdExcel.CommandText = "SELECT * From [" + sheetName + "] Where Name IS NOT NULL AND NOT Name=''";
                     odaExcel.SelectCommand = cmdExcel;
                     odaExcel.Fill(dt);
                     connExcel.Close();
                    }
                 }
              }                   
             //Insert Call Dispositions table bulk upload
             conString = ConfigurationManager.ConnectionStrings["exportDataToExcel"].ConnectionString;
             using (SqlConnection con = new SqlConnection(conString))
             {
              using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(con))
                {
                   TempData["TotalInsertCount"] = dt.Rows.Count;
                   foreach (DataColumn col in dt.Columns)
                            col.ColumnName = col.ColumnName.Trim();

                    //Set the database table name.
                    sqlBulkCopy.DestinationTableName = "dbo.CallDispositions";
                    //[OPTIONAL]: Map the Excel columns with that of the database table                       
                     sqlBulkCopy.ColumnMappings.Add("Name", "Name");
                     sqlBulkCopy.ColumnMappings.Add("TAT", "TAT");
                     sqlBulkCopy.ColumnMappings.Add("Discription", "Discription");
                     con.Open();
                     sqlBulkCopy.WriteToServer(dt); //
                     con.Close();
                 }
              }
          //End
        }
      }
     catch (Exception ex)
     {

     }
     return RedirectToAction("List"); }

用于获取Excel数据并添加数据表的连接字符串

<add name="Excel03ConString" connectionString="Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES'" />