. Net to get the content of the excel table,. net to get the excel

Source: Internet
Author: User

. Net to get the content of the excel table,. net to get the excel

Reference Components and namespaces first

Using Microsoft. Office. Interop. Excel;

Using System. Data. OleDb;

Then upload the excel file to the specified path.

File Upload method omitted

Finally, convert the uploaded excel file to Dataset (copy the following method to use)

Public DataSet seachExcel (string str) // The excel path

{

OleDbDataAdapter da = new OleDbDataAdapter ();

DataSet ds = new DataSet ();

DataTable dt = new DataTable ();

String NameTable = "";

String ConText = "";

Try

{

// Obtain the Excel file path

FileInfo info = new FileInfo (str );

// Obtain the file extension

String fileExt = info. Extension;

// Determine the connection method used

If (fileExt. ToLower () = ". xls ")

{

ConText = "Provider = Microsoft. jet. OLEDB.4.0; Data Source = "+ str +"; Extended Properties = 'excel 8.0; hdr = no; IMEX = 1'; Persist Security Info = false ";

}

Else if (fileExt. ToLower () = ". xlsx ")

{

ConText = "Provider = Microsoft. ACE. OLEDB.12.0; Data Source = "+ str +"; Extended Properties = 'excel 12.0 Xml; hdr = no; IMEX = 1'; Persist Security Info = False ";

}

// Connect to excel

OleDbConnection conn = new OleDbConnection (ConText );

// Open excel

Conn. Open ();

Dt = conn. GetOleDbSchemaTable (OleDbSchemaGuid. Tables, null );

If (dt! = Null & dt. Rows. Count> 0)

{

// Obtain the table name of the sheet1 form

NameTable = dt. Rows [0] ["TABLE_NAME"]. ToString ();

// Obtain the table name of the sheet2 form

// NameTable = dt. Rows [1] ["TABLE_NAME"]. ToString ();

}

String SQL = "select * from [" + NameTable + "]";

Da = new OleDbDataAdapter (SQL, conn );

Try

{

Da. Fill (ds, NameTable); // Fill data in Dataset

}

Catch

{}

Conn. Close ();

}

Catch

{

}

Return ds; // returns the Dataset.

}

 

Related Article

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.