Do not add any Excel DLL reference,CodeIt is very simple, so I will not explain it.
Using system; using system. collections. generic; using system. LINQ; using system. text; using system. data; using system. data. common; namespace ocxmlcreater. excelprovider {public class excelhelper {
// The only thing that needs to be explained is that, in the connection string, HDR = Yes indicates that the first row of the Excel table is used to display the field name (header). If no field name exists, HDR = no public static string connectionstring = @ "provider = Microsoft. jet. oledb.4.0; Data Source = D: \ workspace \ mydocument \ samples2.xlsx; extended properties = "" Excel 8.0; HDR = yes ;"""; /// <summary> /// read the Excel worksheet and return dataset /// </Summary> /// <Param name = "connectionstring"> Excel connection string </param> // /<Param name = "commandstring"> query statement, for example: "select ID, username, useraddress from [sheet1 $]" </param> // <returns> </returns> Public static dataset getexceldataset (string connectionstring, string commandstring) {dbproviderfactory factory = dbproviderfactories. getfactory ("system. data. oledb "); dbdataadapter adapter = factory. createdataadapter (); dbcommand selectcommand = factory. createcommand (); selectcommand. commandtext = commandstring; // commandstring example: "select ID, username, useraddress from [sheet1 $]" dbconnection connection = factory. createconnection (); connection. connectionstring = connectionstring; selectcommand. connection = connection; adapter. selectcommand = selectcommand; dataset cities = new dataset (); adapter. fill (cities); connection. close (); Return cities ;}}}