0
私は外部ファイルからレコードをインポートするWebアプリケーションを開発しています。つまり、SQL ServerデータベーステーブルにMs Excelがあります。 Excelから新しいレコードが ファイル私は6 私のコントローラコードがあるasp.new MVC 5エンティティを使用しています:excelファイルからSQLテーブルの既存のレコードを更新する
public JsonResult UploadExcel(Student student, HttpPostedFileBase FileUpload)
{
List<string> data = new List<string>();
if (FileUpload != null)
{
if (FileUpload.ContentType == "application/vnd.ms-excel" || FileUpload.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
string filename = FileUpload.FileName;
string targetpath = Server.MapPath("~/Doc/");
FileUpload.SaveAs(targetpath + filename);
string pathToExcelFile = targetpath + filename;
var connectionString = "";
var ds = new DataSet();
DataTable dtable = ds.Tables["ExcelTable"];
string sheetName = "Sheet1";
var excelFile = new ExcelQueryFactory(pathToExcelFile);
var studentname = from a in excelFile.Worksheet<Student>(sheetName) select a;
var artistAlbums = from a in excelFile.Worksheet<Student>(sheetName) select a;
if (filename.EndsWith(".xls"))
{
connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", pathToExcelFile);
}
else if (filename.EndsWith(".xlsx"))
{
connectionString = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0 Xml;HDR=YES;IMEX=1\";", pathToExcelFile);
}
var adapter = new OleDbDataAdapter("SELECT * FROM [Sheet1$]", connectionString);
adapter.Fill(ds, "ExcelTable");
foreach (var a in artistAlbums)
{
try
{
if (a.STUDENTNAME != "" && a.COURSEID != null && a.TEACHERID != null && a.PHOTOID != null)
{
Student TU = new Student();
TU.STUDENTID = a.STUDENTID;
TU.STUDENTNAME = a.STUDENTNAME;
TU.COURSEID = a.COURSEID;
TU.TEACHERID = a.TEACHERID;
TU.PHOTOID = a.PHOTOID;
db.Students.Add(TU);
db.SaveChanges();
}
else
{
data.Add("<ul>");
if (a.STUDENTNAME == "") data.Add("<li> Name is required</li>");
if (a.COURSEID == null) data.Add("<li> CourseId is required</li>");
if (a.TEACHERID == null) data.Add("<li> TeacherId is required</li>");
if (a.PHOTOID == null) data.Add("<li> PhotoId is required</li>");
data.Add("</ul>");
data.ToArray();
return Json(data, JsonRequestBehavior.AllowGet);
}
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
}
if ((System.IO.File.Exists(pathToExcelFile)))
{
System.IO.File.Delete(pathToExcelFile);
}
return Json("success", JsonRequestBehavior.AllowGet);
}
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);
}
}