<summary>
Populating data in an Excel table into a dataset
</summary>
<param name= "filenameurl" >excel file path (including file name) </param>
<param name= The file name of the "table" >excel </param>
<returns></returns>
public static DataSet Execleds (string filenameurl, String table)
{
String strconn = "provider=microsoft.ace.oledb.12.0; Persist Security info=false;data source= "+ Filenameurl +"; Extended properties= ' Excel 12.0; Hdr=yes; Imex=1 ' ";
OleDbConnection conn = new OleDbConnection (strconn);
OleDbDataAdapter Odda = new OleDbDataAdapter ("SELECT * from [sheet1$]", conn);
DataSet ds = new DataSet ();
Odda. Fill (ds, table);
return DS;
}
Application examples
<summary>
Import Excel Information
</summary>
<param name= "Context" ></param>
<param name= "Returnmsg" ></param>
<returns></returns>
public bool Importinfo (HttpContext context, ref string returnmsg)
{
bool IsError = true;
Try
{
String FilePath = httpcontext.current.request.files["File1"]. FileName; Get the uploaded file name
if (FilePath! = "")
{
String Isxls = System.IO.Path.GetExtension (FilePath). ToString (). ToLower ();//Gets the file's suffix name
if (Isxls = = ". xls" | | Isxls = = ". xlsx")//Determine if it is an Excel file
{
String fileroot = ""; File Save path
string filename = DateTime.Now.ToString ("yyyymmddhhmmssfff") + isxls;//Change the file name (named with current time)
httpcontext.current.request.files["File1"]. SaveAs (context. Server.MapPath (Fileroot + FileName);//Save the uploaded file
DataSet ds = Execleds (HttpContext.Current.Server.MapPath (fileroot + filename), filename),//Read the contents of the Excel file to populate the dataset
datarow[] Dr = ds. Tables[0]. Select ();//Set a DataRow array
int rowsnum = ds. Tables[0]. Rows.Count; Total line
if (Rowsnum = = 0)//Determine if Excel is empty
{
returnmsg = "Excel table is empty table, no data!";
return false;
}
DataTable dt = ds. Tables[0];
String code = "";
for (int i = 0; i < Dr. Length; i++)
{
Data processing
if (Dr[i]. Table.Columns.Contains ("Row header") && dr[i]["row header"]! = NULL)
//{
if (dr[i]["row header"]. ToString (). Trim () = = "")
//{
Returnmsg = "No." + (i + 2) + "line of * * cannot be empty, please modify and re-import!";
return false;
//}
Code = dr[i]["Row header"]. ToString (). Trim ();
//}
Else
//{
returnmsg = "Missing * * column, please modify and re-import!";
return false;
//}
}
return isError;
}
Else
{
returnmsg = "Only Excel files can be selected!";
return false;
}
}
Else
{
returnmsg = "Please select the Excel file to import!";
return false;
}
}
catch (Exception ex)
{
Returnmsg = "The system has an unknown error, please contact the system administrator!" ";
return false;
}
}
C # Populates data inside Excel into a dataset