2017-07-14 61 views
0

我有批量導入excel到sql數據庫,我需要驗證每一行,我使用的是Microsoft.Office.Interop.Excel Services。我正在使用以下代碼:需要驗證行在Excel aps.net MVC

public ActionResult ImportDataAgens() 
{ 
    return View(); 
} 

[HttpPost] 
[ValidateAntiForgeryToken] 
public ActionResult ImportDataAgens(HttpPostedFileBase excelfileRekn) 
{ 
    if (excelfileRekn == null || excelfileRekn.ContentLength == 0) 
    { 
    ViewBag.Error = "Please Select File <br>"; 
    return View("ImportDataAgens"); 
    } 
    else 
    { 
    if (excelfileRekn.FileName.EndsWith("xls") || excelfileRekn.FileName.EndsWith("xlsx")) 
    { 
     string newFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff"); 
     string filename = Path.GetFileName(excelfileRekn.FileName); 
     string DocFileNames = newFileName + "-" + filename; 
     string path = System.IO.Path.Combine(Server.MapPath("~/UploadFile/DataAgen/"), DocFileNames); 
     if (System.IO.File.Exists(path)) 
     System.IO.File.Delete(path); 
     try 
     { 
     excelfileRekn.SaveAs(path); 
     ViewData["Feedback"] = "Upload Complete"; 
     } 
     catch (Exception ex) 
     { 
     ViewData["Feedback"] = ex.Message; 
     } 

     //read data from file excel 

     Excel.Application application = new Excel.Application(); 
     Excel.Workbook workbook = application.Workbooks.Open(path); 
     Excel.Worksheet worksheet = workbook.ActiveSheet; 
     Excel.Range range = worksheet.UsedRange; 
     List<DMInformasiDataAgen> listTempRekn = new List<DMInformasiDataAgen>(); 
     for (int row = 3; row <= range.Rows.Count; row++) 
     { 
     DMInformasiDataAgen rk = new DMInformasiDataAgen(); 
     rk.NamaAgen = ((Excel.Range)range.Cells[row, 2]).Text; 
     rk.NomorIdentifikasiAgen = ((Excel.Range)range.Cells[row, 3]).Text; 
     rk.NomordanTanggalPerjanjian = ((Excel.Range)range.Cells[row, 4]).Text; 
     rk.CreateBy = valueA; 
     rk.UpdateDate = DateTime.Today; 
     listTempRekn.Add(rk); 
     db.DMInformasiDataAgen.Add(rk); 
     db.SaveChanges(); 
     ViewBag.Result = "Successfully Imported"; 
     } 
     return RedirectToAction("Index", "DataAgens"); 
    } 
    else 
    { 
     ViewBag.Error = "This file format is not supported"; 
     return View("ImportDataAgens"); 
    } 
    } 
} 

如何驗證所有行中的數據?

+0

您可以使用數據行或dt.rows驗證數據值[「columnname」]值可以與代碼一起使用,也可以創建正則表達式驗證,以確定您期望使用哪種類型的值。 –

回答

0

您可以爲每種類型創建驗證功能,然後您可以收集所有失敗的行以避免instert列出並向用戶提供信息。

+0

感謝您的支持,我不知道如何在導入文件時從excel中分離行,並在批量導入數據庫時​​驗證行分隔。 –