ASP.net连接Excel的代码
程序员文章站
2024-03-07 22:43:15
首先添加命名空间 复制代码 代码如下: using system.data.oledb; protected void page_load(object sender, e...
首先添加命名空间
using system.data.oledb;
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
strfile = request.querystring["filename"];//从其他页面传过来的文件路径
excel(strfile);
}
}
private void excel(string filepath)
{
try
{
dataset ds = new dataset();
string connstr = "provider=microsoft.jet.oledb.4.0;data source=" + filepath +
";extended properties='excel 8.0; hdr=yes; imex=1'";//连接excel的字符串
string query = "select * from [student$]";//excel中的表名称
oledbcommand olecommand = new oledbcommand(query, new oledbconnection(connstr));
oledbdataadapter oleadapter = new oledbdataadapter(olecommand);
oleadapter.fill(ds, "[student$]");
rowcount = ds.tables[0].rows.count;
gridview1.datasource = ds;
gridview1.databind();
lblmes.text = "上传成功,数据如下所示,请确认:";//lblmes为label,显示提示信息
}
catch (oledbexception)
{
string filename = filepath.substring(filepath.lastindexof('/') + 1);
lblmes.text = "错误!请确认上传文件是否正确!当前上传的文件为:" + filename;
lbtnsure.visible = false;
}
catch(exception ee)
{
lblmes.text = ee.message;
}
}
在asp.net用c#建立动态excel
复制代码 代码如下:
using system.data.oledb;
protected void page_load(object sender, eventargs e)
{
if (!ispostback)
{
strfile = request.querystring["filename"];//从其他页面传过来的文件路径
excel(strfile);
}
}
private void excel(string filepath)
{
try
{
dataset ds = new dataset();
string connstr = "provider=microsoft.jet.oledb.4.0;data source=" + filepath +
";extended properties='excel 8.0; hdr=yes; imex=1'";//连接excel的字符串
string query = "select * from [student$]";//excel中的表名称
oledbcommand olecommand = new oledbcommand(query, new oledbconnection(connstr));
oledbdataadapter oleadapter = new oledbdataadapter(olecommand);
oleadapter.fill(ds, "[student$]");
rowcount = ds.tables[0].rows.count;
gridview1.datasource = ds;
gridview1.databind();
lblmes.text = "上传成功,数据如下所示,请确认:";//lblmes为label,显示提示信息
}
catch (oledbexception)
{
string filename = filepath.substring(filepath.lastindexof('/') + 1);
lblmes.text = "错误!请确认上传文件是否正确!当前上传的文件为:" + filename;
lbtnsure.visible = false;
}
catch(exception ee)
{
lblmes.text = ee.message;
}
}
在asp.net用c#建立动态excel