C # Read an Excel worksheet

Source: Internet
Author: User

Recently, I have been dealing with worksheet problems, and I used C # To read table data. The method is as follows:

using Data=System.Data;
/// <Summary> /// obtain the data in a worksheet /// </Summary> /// <Param name = "FILENAME"> file name and path </param> /// <Param name = "queryworksheetname"> the queried worksheet </param> /// <returns> the Retrieved Data </returns> public data. datatable getdatafromworksheet (string filename, string queryworksheetname) {data. datatable dtresult = NULL; string connstr = "provider = Microsoft. jet. oledb.4.0; Data Source = {0}; extended properties = \ "Excel 8.0; HDR = no; IMEX = 1 ;\""; string query = "select * from [" + queryworksheetname + "$]"; try {using (oledbcommand olecommand = new oledbcommand (query, new oledbconnection (string. format (connstr, filename) {using (oledbdataadapter oleadapter = new oledbdataadapter (olecommand) {data. dataset mydataset = new data. dataset (); oleadapter. fill (mydataset); dtresult = mydataset. tables [0] ;}}catch {dtresult = NULL;} return dtresult ;}

The preceding method reads the data in a worksheet to the able, but note the following:

Assume that there is no data in the first four rows of a table and there is data starting from the fifth row. Then, the first row in the returned datatable is the fifth row in the worksheet, that is, only the pen with data is read, this is also true for columns. Note that if the first three columns in a table have no data ~ Five columns have data, 6th columns have no data, and the seventh column has data. After the data is read to the able table, the first three columns of the table are discarded, but the 6th columns are not discarded, because both the left and right columns have data.

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.