C # Read the cell data of the specified area in the Excel worksheet
Source: Internet
Author: User
Use C # To read the cell data of the specified area in the Excel worksheet
Use the oledbdataadapter object in ADO. Net to read the Excel file. By default, the cell in the first row with data in the worksheet is the field name. If you do not want to use the cell in the first row of data in the workbook as the field name of the data table, you can use the second instance in this article.
Create a data source connection string for the connection object: "provider = Microsoft. jet. oledb.4.0; Data Source = Excel file physical path + "; extended properties = Excel 8.0"; these two instances are created in Excel 2000 or later versions.
Instance 1 reads all data in the Excel worksheet
Read all data in Excel worksheet 1 (worksheet name: sheet1). The SQL statement in the oledbdataadapter object should be: "select field list from [worksheet name $]".
Sample Code:
Public void readexcel (string sexcelfile)
{
String sconnectionstring = "provider = Microsoft. Jet. oledb.4.0; Data Source =" + sexcelfile + "; extended properties = Excel 8.0 ";
Oledbconnection connection = new oledbconnection (sconnectionstring );
Oledbdataadapter ADP = new oledbdataadapter ("select * from [sheet1 $]", connection );
Dataset DS = new dataset ();
ADP. Fill (DS, "book1 ");
Grd_excel.datasource = Ds. Tables ["book1"]. defaultview;
Grd_excel.databind ();
}
Instance 2 reads data from the selected area of the Excel worksheet
First, in the workbook, left-click the area to be defined as the table, and select 'insert'> 'name'> 'define' from the menu ', in the 'define name' dialog box, enter the table name testtable and OK.
The SQL statement should be: Select * From testtable.
Sample Code:
Public void readexcel (string sexcelfile)
{
String sconnectionstring = "provider = Microsoft. Jet. oledb.4.0; Data Source =" + sexcelfile + "; extended properties = Excel 8.0 ";
Oledbconnection connection = new oledbconnection (sconnectionstring );
Oledbdataadapter ADP = new oledbdataadapter ("select * From testtable", connection );
Dataset DS = new dataset ();
ADP. Fill (DS, "book1 ");
Grd_excel.datasource = Ds. Tables ["book1"]. defaultview;
Grd_excel.databind ();
}
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.