1
從Excel導入到應用程序中,然後使用asp.net mvc和wcf保存在數據庫中。 它由於空字段而生成錯誤。我檢查我的數據庫和我的代碼,我看到,我允許在這些領域爲空如何檢查excel導入中的空字段
請參閱我的控制器下面。
控制器
public ActionResult ImportCacExcel(HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
var bodsList = new List<CAC>();
if (FileUpload != null)
{
HttpPostedFileBase file = Request.Files["FileUpload"];
if (true)//FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
using (var package = new ExcelPackage(file.InputStream))
{
var currentSheet = package.Workbook.Worksheets;
// if(currentSheet.Count)
var workSheet = currentSheet.First();
var noOfCol = workSheet.Dimension.End.Column;
var noOfRow = workSheet.Dimension.End.Row;
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var bod = new CAC();
bod.RC_NUMBER = workSheet.Cells[rowIterator, 1].Value.ToString();//.ToString().Trim();
bod.COMPANY_NAME = workSheet.Cells[rowIterator, 2].Value.ToString();//.ToString().Trim();
bod.OWNERSHIP_STRUCTURE = workSheet.Cells[rowIterator, 3].Value.ToString();//.ToString().Trim();
bod.ADDRESS_STREET = workSheet.Cells[rowIterator, 4].Value.ToString();
bod.ADDRESS_CITY = workSheet.Cells[rowIterator, 5].Value.ToString();
bod.ADDRESS_STATE = workSheet.Cells[rowIterator, 6].Value.ToString();
bod.ADDRESS_PMB = workSheet.Cells[rowIterator, 7].Value.ToString();
bod.ADDRESS_POBOX = workSheet.Cells[rowIterator, 8].Value.ToString();
bod.ADDRESS_LGA = workSheet.Cells[rowIterator, 9].Value.ToString();
try
{
bod.DATE_OF_REGISTRATION = Convert.ToDateTime("01/01/" + workSheet.Cells[rowIterator, 4].Value);//.ToString().Trim();
}
catch (Exception e)
{
data.Add("Bad Date format for item at row " + rowIterator);
}
bod.ACTION_STATUS = 1;
bod.CREATED_DATE = DateTime.Now;
bodsList.Add(bod);
}
}
foreach (var item in bodsList)
{
_cacService.AddCac(item);
}
return RedirectToAction("Index");
}
else
{
data.Add("<ul>");
data.Add("<li>Only Excel file format is allowed</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
data.Add("<ul>");
if (FileUpload == null) data.Add("<li>Please choose Excel file</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
請我怎麼改變我的控制器代碼ckeck如果像
- RC_NUMBER
- COMPANY_NAME
- OWNERSHIP_STRUCTURE
爲空或空,它應該指示給用戶。 但如果字段,如
- ADDRESS_STREET
- ADDRESS_CITY
- ADDRESS_STATE
- ADDRESS_PMB
- ADDRESS_POBOX
- ADDRESS_LGA
是null或空,它應該增加空的excel,並將null保存到數據庫。
**非常感謝,它的工作。**請問我爲了防止未來發生。我用asp.net mvc使用wcf。在wcf中,我使用了數據註釋。但是,在使用服務時,它並未實現數據註釋。這就是爲什麼我有你幫助我解決的錯誤。我如何使它實現數據註釋 – Gbenga
@Genga這將是一個全新的問題:)如果這已經回答了您的問題,您可以考慮將其標記爲答案。 –