0

我已经尝试在 ASP.NET MVC 5 应用程序上实现这个https://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 。

//见下面的代码

   [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {

        var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
        if (file != null && file.ContentLength > 0)
        {
            var extension = Path.GetExtension(file.FileName);
            var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
            if (System.IO.File.Exists(excelFile))
            {
                System.IO.File.Delete(excelFile);
            }
            else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
            {
                file.SaveAs(excelFile);//WORKS FINE
                //BEGINING OF IMPORT
                FileInfo eFile = new FileInfo(excelFile);
                using (var excelPackage = new ExcelPackage(eFile))
                {
                    if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
                    { ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
                    else
                    {
                        var worksheet = excelPackage.Workbook.Worksheets[1];
                        if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;

                        else
                        {
                            var lastRow = worksheet.Dimension.End.Row;
                            while (lastRow >= 1)
                            {
                                var range = worksheet.Cells[lastRow, 1, lastRow, 3];
                                if (range.Any(c => c.Value != null))
                                { break; }
                                lastRow--;
                            }
                            using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
                            {
                                for (var row = 2; row <= lastRow; row++)
                                {
                                    var newPerson = new personalDetails
                                    {
                                        identificationType = worksheet.Cells[row, 1].Value.ToString(),
                                        idNumber = worksheet.Cells[row, 2].Value.ToString(),
                                        idSerial = worksheet.Cells[row, 3].Value.ToString(),
                                        fullName = worksheet.Cells[row, 4].Value.ToString(),
                                        dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
                                        gender = worksheet.Cells[row, 6].Value.ToString()
                                    };
                                    DB.personalDetails.Add(newPerson);
                                    try { db.SaveChanges(); }
                                    catch (Exception) { }
                                }
                            }
                        }

                    }

                }//END OF IMPORT
                ViewBag.Message = "Your file was successfully uploaded.";
                return RedirectToAction("Index");
            }

            ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
            return View();
        }
        else
        {
            ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
            return View();
        }
    }

请参阅图片错误 任何帮助将不胜感激队友。

4

1 回答 1

0

你可以这样做:

public bool readXLS(string FilePath)
{
    FileInfo existingFile = new FileInfo(FilePath);
    using (ExcelPackage package = new ExcelPackage(existingFile))
    {
        //get the first worksheet in the workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
        int colCount = worksheet.Dimension.End.Column;  //get Column Count
        int rowCount = worksheet.Dimension.End.Row;     //get row count
        string queryString = "INSERT INTO tableName VALUES";        //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
        string eachVal = "";
        bool status;
        for (int row = 1; row <= rowCount; row++)
        {
            queryString += "(";
            for (int col = 1; col <= colCount; col++)
            {
                eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
                queryString += "'" + eachVal + "',";
            }
            queryString = queryString.Remove(queryString.Length - 1, 1);    //removing last comma (,) from the string
            if (row % 1000 == 0)        //On every 1000 query will execute, as maximum of 1000 will be executed at a time. 
            {
                queryString += ")";
                status = this.runQuery(queryString);    //executing query
                if (status == false)
                    return status;
                queryString = "INSERT INTO tableName VALUES";
            }
            else
            {
                queryString += "),";
            }
        }
        queryString = queryString.Remove(queryString.Length - 1, 1);    //removing last comma (,) from the string
        status = this.runQuery(queryString);    //executing query
        return status;
    }
}

详情:http ://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/

于 2018-08-30T11:39:36.587 回答