asp.net动态获取Excel表名的函数代码
程序员文章站
2024-03-08 09:14:33
复制代码 代码如下: public string getexcelfirsttablename(string excelfilename) { string tablena...
复制代码 代码如下:
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\";data 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读取excel动态获取表名
复制代码 代码如下:
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 ++ ) //第一行为标题,不读取
{
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();