asp.net function code to dynamically get Excel table names
Last Update:2017-02-28
Source: Internet
Author: User
Copy Code The code is as follows:
public 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);
for (int i = 0; i < dt. Rows.Count; i++)
{
tablename = dt. ROWS[I][2]. ToString (). Trim ();
View Sourceprint?1}
}
}
return tablename;
}
asp.net read Excel dynamic fetch table name
Copy Code The code is as follows:
String a=file1.postedfile.filename.tostring ();
String excelfilepath=a;
Excel.Application myexcel=new Excel.applicationclass ();
object omissing = System.Reflection.Missing.Value;
MyExcel.Application.Workbooks.Open (Excelfilepath,omissing,omissing,omissing,omissing,omissing,omissing, omissing,omissing,omissing,omissing,omissing,omissing,omissing,omissing);
Excel.Workbook myBook = myexcel.workbooks[1];
Excel.Worksheet MySheet = (excel.worksheet) mybook.worksheets[1];
Response.Write (Mysheet.name);
String Name=mysheet.name;
System.Data.DataTable dt=new System.Data.DataTable ("MyTable");
Dt. Columns.Add ("F1", System.Type.GetType ("System.String"));
Dt. Columns.Add ("F2", System.Type.GetType ("System.String"));
Dt. Columns.Add ("F3", System.Type.GetType ("System.String"));
Dt. Columns.Add ("F4", System.Type.GetType ("System.String"));
Dt. Columns.Add ("F5", System.Type.GetType ("System.String"));
DataSet myds = new DataSet ();
MYDS.TABLES.ADD (DT);
DataRow Myrow;
Myds.clear ();
for (int i = 2; I <= 4; i + +)//First behavior title, not read
{
Myrow = myds.tables["MyTable"]. NewRow ();
for (int j = 1; J <= 5; j + +)
{
Excel.Range r= (Excel.Range) mysheet.cells[i,j];
String strvalue=r.text.tostring ();
String Aa=strvalue;
String Columnname= "F" +j.tostring ();
Myrow[columnname]=strvalue;
}
myds.tables["MyTable"]. Rows.Add (Myrow);
// }
Myexcel.quit ();
datagrid1.datasource=myds.tables["MyTable"]. DefaultView;
Datagrid1.databind ();