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 #