asp.net - how to do validation in sql bulk copy upload -
i created mvc4 application upload data using excel file store in database table called tbl_hei_student
.
[httppost] [acceptverbs(httpverbs.post)] public actionresult student(httppostedfilebase fileupload1) { try { string constring = string.empty; //upload , save file if (request.files["fileupload1"].contentlength > 1) { try { string excelpath = path.combine(httpcontext.server.mappath("~/content/"), path.getfilename(fileupload1.filename)); fileupload1.saveas(excelpath); string extension = path.getextension(fileupload1.filename); switch (extension) { case ".xls": //excel 97-03 constring = configurationmanager.connectionstrings["excel03constring"].connectionstring; break; case ".xlsx": //excel 07 or higher constring = configurationmanager.connectionstrings["excel07+constring"].connectionstring; break; default: this.setnotification("the file type submitted invalid", notificationenumeration.error); return redirecttoaction("student", "excel"); } constring = string.format(constring, excelpath); } try { using (oledbconnection excel_con = new oledbconnection(constring)) { excel_con.open(); datatable dtexceldata = new datatable(); string query = "select " + "s1.hec_id, " + "s1.student_personal_id, " + "s1.date_of_birth " ; using (oledbdataadapter oda = new oledbdataadapter(query, excel_con)) { oda.fill(dtexceldata); } //if (dtexceldata.defaultview.count < 0) // { // throw new exception("your data sheet empty. pleaswe upload another."); // } string consstring = configurationmanager.connectionstrings["constr"].connectionstring; using (sqlconnection con = new sqlconnection(consstring)) { using (sqlbulkcopy sqlbulkcopy = new sqlbulkcopy(con, sqlbulkcopyoptions.checkconstraints | sqlbulkcopyoptions.firetriggers | sqlbulkcopyoptions.keepnulls | sqlbulkcopyoptions.tablelock | sqlbulkcopyoptions.useinternaltransaction | sqlbulkcopyoptions.keepidentity, null)) { //set database table name sqlbulkcopy.destinationtablename = "tbl_hei_student"; sqlbulkcopy.bulkcopytimeout = 0; sqlbulkcopy.columnmappings.add("hec_id", "hec_id"); sqlbulkcopy.columnmappings.add("student_personal_id", "student_personal_id"); sqlbulkcopy.columnmappings.add("date_of_birth", "date_of_birth"); con.open(); { con.close(); } } } } } } } }
in table have following fields capture data upload using excel file
column name | data type hec_id | nvarchar(100) student_personal_id | nvarchar(100) date_of_birth | datetime
in excel have hundreds of rows ,
i terminate upload action, if 1 data field in wrong format date_of_birth
field
before inserting database, fetch variable , check
datetime date = datetime.parseexact(inputstring, formatstring, system.globalization.cultureinfo.invariantculture)
Comments
Post a Comment