Original:http://www.cnblogs.com/xiaopin/archive/2011/03/31/2001199.html
This code currently only supports XLS files and does not support xlsx files.
protectedvoidBtnimport_click (Objectsender, EventArgs e)
{
if(Fileupload1.hasfile = =false)//HasFile used to check if FileUpload has a specified file
{
Response.Write ("<script>alert (' Please select Excel file ') </script>");
return;//when there is no file, return
}
stringIsxls = System.IO.Path.GetExtension (fileupload1.filename). ToString (). ToLower ();//System.IO.Path.GetExtension getting the file name extension
if(Isxls! =". xls")
{
Response.Write ("<script>alert (' Can only select Excel Files ') </script>");
return;//When you select an Excel file that is not, return
}
stringfilename = fileupload1.filename;//get execle filename datetime date function
stringSavepath = Server.MapPath (("upfiles\\") + filename);//Server.MapPath obtaining a virtual server relative path
Fileupload1.saveas (Savepath);//SaveAs saves uploaded file contents on the server
DataSet ds = excelsqlconnection (savepath, filename);//calling a custom method
datarow[] Dr = ds. tables[0]. Select ();//define a DataRow array
intRowsnum = ds. tables[0]. Rows.Count;
if(Rowsnum = =0)
{
Response.Write ("<script>alert (' Excel table is empty table, no data! ') </script>");//prompt the user when the Excel table is empty
}
Else
{
for(inti =0; I < Dr. Length; i++)
{
//In front of you need to create a "upfiles" folder, the others do not have to control, you just need to get the value of Excel in the following way, and then put these values in your way to insert into the database
stringtitle = dr[i]["title"]. ToString ();
stringLinkurl = dr[i]["Link Address"]. ToString ();
stringCategoryName = dr[i]["category"]. ToString ();
stringCustomerName = dr[i]["content providers"]. ToString ();
//Response.Write ("<script>alert" (' Import content: ' + ex. Message + "') </script>");
}
Response.Write ("<script>alert (' excle table import succeeded! '); </script>");
}
}
#regionConnect Excel to read Excel data and return DataSet data collection
/// <summary>
///connect Excel to read Excel data and return DataSet data collection
/// </summary>
/// <param name= "filepath" >Excel Server Path</param>
/// <param name= "TableName" >Excel table name</param>
/// <returns></returns>
PublicStaticSystem.Data.DataSet Excelsqlconnection (stringFilePathstringTableName)
{
stringStrcon ="Provider=Microsoft.Jet.OLEDB.4.0;Data source="+ filepath +"; Extended properties= ' Excel 8.0; Hdr=yes;imex=1 '";
OleDbConnection excelconn =NewOleDbConnection (Strcon);
Try
{
stringstrcom =string. Format ("SELECT * FROM [sheet1$]");
Excelconn.open ();
OleDbDataAdapter mycommand =NewOleDbDataAdapter (strcom, excelconn);
DataSet ds =NewDataSet ();
Mycommand.fill (DS,"["+ TableName +"$]");
Excelconn.close ();
returnds
}
Catch
{
Excelconn.close ();
returnNULL;
}
}
#endregion
asp.net--Importing Excel data