Basic data import is often involved in projects. In most cases, you need to obtain data from Excel. The following describes how to extract data from an Excel file to Dataset:
/// <Summary>
/// Extract the table data according to the path of the Excel file
/// </Summary>
/// <Param name = "path"> Excel file path </param>
/// <Returns> </returns>
Public static dataset getdatafromexcel (string path)
{
String strconn = "provider = Microsoft. Jet. oledb.4.0;" + "Data Source =" + path + ";" + "extended properties = Excel 8.0 ;";
Oledbconnection conn;
Dataset DS = new dataset ();
Try
{
Conn = new oledbconnection (strconn );
Conn. open ();
// Return the Excel schema, including the name, type, Creation Time, and modification time of each sheet.
Datatable dtsheetname = conn. getoledbschematable (oledbschemaguid. Tables, new object [] {null, "table "});
// String array containing the table name in Excel
String [] strtablenames = new string [dtsheetname. Rows. Count];
String [] strtables = new string [dtsheetname. Rows. Count];
Int K;
String temp;
String [] IDs = new string [dtsheetname. Rows. Count];
For (k = 0; k <dtsheetname. Rows. Count; k ++)
{
Temp = dtsheetname. Rows [k] ["table_name"]. tostring ();
Strtables [k] = temp. Trim ('$ ');
Strtablenames [k] = temp;
}
Oledbdataadapter mycommand = NULL;
For (k = 0; k <dtsheetname. Rows. Count; k ++)
{
Datatable dt = new datatable ();
// Query data from the specified table. All the table columns can be selected first.
String strexcel = "select * from [" + strtablenames [k] + "]";
Mycommand = new oledbdataadapter (strexcel, strconn );
Mycommand. Fill (DT );
DT. tablename = strtables [k];
DS. Tables. Add (DT );
}
Conn. Close ();
}
Catch (exception ex)
{
// Write the error log...
String strouput = string. Format ("failed to get data in the file, error message: {0}, exception {1} \ n", Ex. Message, Ex. innerexception );
// Write the information to the log output file
Dllcomm. tp_writeapplogfileex (dllcomm. g_applogfilename, strouput );
}
Return Ds;
}