ASP. NET import data from an Excel file to a database (note)

Source: Internet
Author: User

HTML Code :

<% @ Page Language = "C #" autoeventwireup = "true" codefile = "default. aspx. cs" inherits = "_ default" %> <! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> 

 

C # code:

Using system; using system. data; using system. configuration; using system. collections; using system. web; using system. web. security; using system. web. ui; using system. web. UI. webcontrols; using system. web. UI. webcontrols. webparts; using system. web. UI. htmlcontrols; using system. text; using system. data. oledb; using system. io; public partial class _ default: system. web. UI. page {protected void page_load (Object sender, Eventargs e) {This. initpage () ;}/// <summary> /// save a able through viewstate. used to add data to the database after the actual situation // </Summary> Public datatable sampldatatable {get {If (viewstate ["sampldatatable"] = NULL) return New datatable (); return (datatable) viewstate ["sampldatatable"];} set {viewstate ["sampldatatable"] = value ;}} private void initpage () {This. errordiv. visible = false; this. confrimdiv. visible = false ;} Protected void btnimport_click (Object sender, eventargs e) {// get the file name string filename = This. excelfile. filename; // absolute path string Path = "~ /EXCEL/"+ filename; Path = server. mappath (PATH); try {// temporarily save this on the service. excelfile. saveas (PATH); // read the content in the Excel file in the specified path and convert it to datatable exceldt = importtodataset (PATH); // declare the error message string stringbuilder errorbuiler = new stringbuilder (); /// check the Excel datatable if (validate (exceldt, errorbuiler) stored in the memory) {// if the check succeeds, use viewstate to save the data in the dataset, sampldatatable = exceldt is used when saving data to the database; // The page gridview data binding is used to display data from the exce L read the data for the user to confirm this. gvconfirm. datasource = sampldatatable; this. gvconfirm. databind (); this. confrimdiv. visible = true; this. buttondiv. visible = true;} else {// If the detection fails, the related error message this. errordiv. visible = true; this. errorarea. value = errorbuiler. tostring () ;}} catch (exception ex) {This. errordiv. visible = true; this. errorarea. value = ex. message;} finally {// close, delete the object if (file. exists (PATH) file. dele Te (PATH) ;}/// <summary> // verify the specified Excel rule (number of columns) /// </Summary> /// <Param name = "exceldt"> </param> /// <Param name = "errorbuiler"> </param> /// <returns> </returns> Public bool validate (datatable exceldt, stringbuilder errorbuiler) {bool result = true; If (exceldt. columns. count! = 5) // suppose it is five columns {result = false; int Difference = exceldt. columns. count-5; If (difference> 0) errorbuiler. appendline ("More Excel files to be imported" + difference. tostring () + "column"); else errorbuiler. appendline ("fewer Excel files to be imported" + (-difference ). tostring () + "column");} else {// foreach (datarow row in exceldt. rows) // {// If (exists (row [0]. tostring () // {// result = false; // errorbuiler. appendline ("content" + "'" + row [2]. tostr Ing () + "'" + "already exists! "); //} Return result;} protected void btnconfirm_click (Object sender, eventargs E) {// write the data displayed in the gridview (actually saved in viewstate) to the database if (adddatatable (sampldatatable, 0) {page. clientscript. registerstartupscript (page. getType (), "insertsuccess", "<SCRIPT> alert ('import successful! '); Window. location. href = 'default. aspx '; </SCRIPT> ");} else {page. clientscript. registerstartupscript (page. getType (), "insertfailure", "<SCRIPT> alert ('import failed! Please try again '); </SCRIPT> ") ;}} private bool adddatatable (datatable DT, int p) {bool result = true; string SQL = builderinsertsql (DT, P ); try {// execute the SQL statement dbhelper. executesql (); Return true;} catch {result = false;} return result;} private string builderinsertsql (datatable DT, int P) {// traverse datatable and splice to add the string return "";} private bool adddatatable (datatable sampldatatable, object P, int P_3) {Throw new Exception ("the method or operation is not implemented. ");} /// <summary> /// read the Excel content in the specified path to the able /// </Summary> /// <Param name = "path"> </param> /// <returns> </returns> Public datatable importtodataset (string path) {string strconn = "provider = Microsoft. ace. oledb.12.0; "+" Data Source = "+ path +"; "+" extended properties = 'excel 12.0; HDR = yes; IMEX = 1'; "; oledbconnection conn = new oledbconnect Ion (strconn); try {datatable dt = new datatable (); If (conn. State! = Connectionstate. open) Conn. open (); string strexcel = "select * from [sheet1 $]"; oledbdataadapter adapter = new oledbdataadapter (strexcel, Conn); adapter. fill (DT); Return DT;} catch (exception ex) {Throw new exception (ex. message);} finally {If (Conn. state! = Connectionstate. Closed) Conn. Close ();}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.