Get the first table name of an Excel file in C #

Source: Internet
Author: User

2. Open and enter data in database mode
This way the XLS file is located in the same directory as the database, where the XLS file is considered a database table, the table name is the file name (without extension).
function Importexceltodataset (string filepath,string sheet) function: Reads data from the XLS into the dataset and returns the DataSet object.

Private DataSet Importexceltodataset (string filepath/* is the path to the file directory */, String sheet/* table name is the file name (without extension) */)
{

String strconn;

String Getsheet;

Getsheet = "SELECT * FROM [" + Sheet + "]";

strconn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data source=" + FilePath + "; Extended Properties=excel 8.0; ";

OleDbConnection conn = new OleDbConnection (strconn);

OleDbDataAdapter mycommand = new OleDbDataAdapter (Getsheet, strconn);

DataSet myDataSet = new DataSet ();

Try
{

Mycommand.fill (myDataSet);

}

catch (Exception ex)
{

MessageBox.Show ("The Excel file's worksheet name is incorrect," + ex.) Message);

}

return mydataset;

}


<summary>
Get the first table name of an Excel file in C #
The default value for the first table name in an Excel file is sheet1$, but it is sometimes changed to another name. If you need to read and write Excel files in C # using OLE DB, you need to know what the name is. The following code is the implementation of this function:
</summary>
<param name= "Excelfilename" ></param>
<returns></returns>
public static string Getexcelfirsttablename (String excelfilename)
{
string tableName = null;
if (file.exists (excelfilename))
{
using (OleDbConnection conn = new OleDbConnection ("Provider=microsoft.jet." +
"OLEDB.4.0; Extended properties=\ "Excel 8.0\";D ata source= "+ excelfilename))
{
Conn. Open ();
DataTable DT = conn. GetOleDbSchemaTable (OleDbSchemaGuid.Tables, NULL);
tableName = dt. ROWS[0][2]. ToString (). Trim ();
}
}
return tableName;
}

Get the first table name of an Excel file in C #

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.