Excel 파일을 업로드하고 ASP.NET MVC를 사용하여 데이터베이스에 저장합니다. 나는 성공했다 :
Excel 파일 가져 오기
데이터베이스에 저장
아래 내 컨트롤러를 참조하십시오.
제어 장치
public ActionResult ImportCountriesExcel(HttpPostedFileBase FileUpload)
{
string data = "";
var notif = new UINotificationViewModel()
{
notif_message = "Record Saved successfully",
notif_type = NotificationType.SUCCESS,
};
var bodsList = new List<COUNTRIES>();
if (FileUpload != null)
{
// tdata.ExecuteCommand("truncate table OtherCompanyAssets");
HttpPostedFileBase file = Request.Files["FileUpload"];
if (true)//FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
try {
string message = "";
using (var package = new ExcelPackage(FileUpload.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 COUNTRIES();
bod.COUNTRY_CODE = Convert.ToString(workSheet.Cells[rowIterator, 1].Value);
if (bod.COUNTRY_CODE == "")
message += "<li> Country Code is empty at row " + rowIterator + "</li>";
bod.COUNTRY_NAME = Convert.ToString(workSheet.Cells[rowIterator, 2].Value);
if (bod.COUNTRY_NAME == "")
message += "<li> Country Name is empty at row " + rowIterator + "</li>";
if (bod.COUNTRY_DESC == "")
message += "<li> Country Desc is empty at row " + rowIterator + "</li>";
bodsList.Add(bod);
}
}
foreach (var item in bodsList)
{
_countriesService.AddCountry(item);
}
return RedirectToAction("Index");
}
catch (Exception e)
{
notif.notif_message = "Application error, Contact the Administrator";
notif.notif_type = NotificationType.ERROR;
}
TempData["notif"] = notif;
return RedirectToAction("Index");
}
else
{
notif.notif_type = NotificationType.ERROR;
//alert message for invalid file format
data += "<ul>";
data += "<li>Only Excel file format is allowed</li>";
data += "</ul>";
notif.notif_message = data;
TempData["notif"] = notif;
return RedirectToAction("Index");
//return Json(data, JsonRequestBehavior.AllowGet);
}
}
else
{
data += "<ul>";
if (FileUpload == null) data += "<li>Please choose Excel file</li>";
data += "</ul>";
notif.notif_message = data;
TempData["notif"] = notif;
return RedirectToAction("Index");
//return Json(data, JsonRequestBehavior.AllowGet);
}
}
내가 가진 문제는 이것입니다
어떻게해야합니까?
중복을 방지하기 위해 데이터베이스에서 기존 항목을 모두 읽고 사전에 저장할 수 있으며 엑셀 행의 각 항목을 반복하는 동안 사전을 확인하여 데이터베이스에 추가하지 않은 경우 해당 항목이 있는지 확인하고 추가 할 수 있습니다. 사전.
var countryDict=db.Countries.ToDictionary(a => a.Code, a => a.Name);
var duplicateItems = new List<string>();
//your existing code goes here
for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++)
{
var countryCode = "Read this from the excel cell";
var countryName = "Read this from the excel cell";
if (countryDict.ContainsKey(countryCode))
{
duplicateItems.Add(countryCode);
}
else
{
countryDict.Add(countryCode,countryName);
//existing code to save
}
}
if(duplicateItems.Any()
{
//This means duplicates exist
}
Trim은 문자열에서 선행 및 후행 공백을 제거하기 위해 호출 할 수있는 방법 일뿐입니다. NULL로 호출하지 않았는지 확인하십시오.
var trimmedValue= someStringVariableWhichCouldBeNull?.Trim();
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다