Use C # To Read Excel and return Dataset

Source: Internet
Author: User

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 ;}}}

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.