Public String saveuploadexcel (httppostedfile HPF) // verify the correctness of the Excel file
{< br> // check whether the size of each file in the file format is valid
If (HPF = NULL | HPF. contentlength <1 | system. io. path. getextension (HPF. filename ). tolower ()! = ". Xls")
{< br> throw new innerexception ("the File Upload Failed or the file format is incorrect .! ");
}
// save the file
try
{< br> string filefullname = makefilename ();
HPF. saveas (filefullname);
return filefullname;
}< br> catch // (exception ex)
{< br> throw new innerexception ("An error occurred while saving the file. "); // + Ex. Message);
}< BR >}
Public String makefilename () // generate an Excel file with a unique file name
{
String filepath = httpcontext. Current. server. mappath (httpcontext. Current. Request. applicationpath) + "\ uploadfiles \ planexcel ";
If (! Directory. exists (filepath ))
Directory. createdirectory (filepath );
String filename = convert. tostring (httpcontext. Current. session ["userid"]) + "_"
+ Datetime. Now. tostring ("yyyymmddhhmmss ")
+ ". Xls ";
Return filepath + "\" + filename;
}
Public datatable readnoheadexceldata (string filefullname) // read the Excel file and return a datatable. You can check this datatable after returning the datatable!
{
String excelnoheadconnstr = "provider = Microsoft. jet. oledb.4.0; Data Source = {0}; extended properties = \ "Excel 8.0; HDR = no; IMEX = 1; \" "; // connection string
Oledbconnection olecn = new oledbconnection ();
Try
{
String currconnstr = string. Format (excelnoheadconnstr, filefullname); // connection string
Olecn. connectionstring = currconnstr;
Datatable dt = new datatable ();
Olecn. open ();
String excelbookname = olecn. getoledbschematable (system. Data. oledb. oledbschemaguid. Tables, null). Rows [0] [2]. tostring ();
If (excelbookname! = String. Empty & excelbookname. Trim ()! = "")
{
String currsqlstr = string. Format (excelsqlstr, excelbookname); // SQL string
Oledbcommand olecmd = new oledbcommand (currsqlstr, olecn );
Oledbdataadapter oledda = new oledbdataadapter (olecmd );
Oledda. Fill (DT );
}
Olecn. Close ();
Return DT;
}
Catch
{
String errormsg = "the Excel file format is incorrect. Please open the file in Excel and check the content and save it again to make sure it is a correct Excel file and then upload it again ";
System. Web. httpcontext. Current. response. Write ("<SCRIPT> alert ('" + errormsg + "') </SCRIPT> ");
Olecn. Close ();
Return NULL;
}
}