zl程序教程

您现在的位置是:首页 >  工具

当前栏目

asp.net读取excel中的数据并绑定在gridview

NetExcelASP数据 读取 绑定 GridView
2023-06-13 09:15:18 时间
前台label,DropDownList,gridview控件

aspx.cs核心代码:
复制代码代码如下:

usingSystem.Data.OleDb;//需要引入命名
publicvoidExcel_Click(objectsender,EventArgse)
{
if(this.AttachmentFile.Value==""&&this.Label1.Text==""&&DropDownList2.SelectedValue=="")
{
Response.Write("<script>window.alert("请选择要导入的文件")</script>");
}
if(this.AttachmentFile.Value!=""&&this.DropDownList2.SelectedValue=="")
{
HttpFileCollectionfiles=HttpContext.Current.Request.Files;
HttpPostedFilepostedFile=files[0];
fileName=System.IO.Path.GetFileName(postedFile.FileName);
if(fileName!="")
{
postedFile.SaveAs("\\\\localhost\\文件夹\\"+fileName);
}
stringstrConn;
strConn="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+"\\\\localhost\\文件夹\\"+fileName+";ExtendedProperties=Excel8.0;";//this.AttachmentFile.Value.ToString()
OleDbConnectionconn=newOleDbConnection(strConn);
conn.Open();
DataTablesheetNames=conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,newobject[]{null,null,null,"TABLE"});
foreach(DataRowdrinsheetNames.Rows)
{
DropDownList2.Items.Add(dr[2].ToString());
}
this.Label1.Text="\\\\localhost\\文件夹\\"+fileName;//this.AttachmentFile.Value.ToString();
conn.Close();
}
if(this.Label1.Text.ToString()!=""&&this.DropDownList2.SelectedValue!="")//&&this.DropDownList1.SelectedValue.ToString()!="全部"
{

//绑定到gridview
GridView1.DataSource=createDataSource(DropDownList2.SelectedValue.ToString(),this.Label1.Text.ToString());//,this.DropDownList1.SelectedValue.ToString()
GridView1.DataBind();


}


}
//以Excel为数据源获取数据集
privateDataSetcreateDataSource(stringselect,stringlable)

{
stringstrCon="Provider=Microsoft.Jet.OLEDB.4.0;DataSource="+lable+";ExtendedProperties=Excel8.0;";
stringstrsql="select登记号码,姓名,日期,签到时间,签退时间,部门from["+select+"]orderby部门,日期,姓名";//excel表格的字段
OleDbConnectionconn=newOleDbConnection(strCon);
OleDbDataAdapterda=newOleDbDataAdapter(strsql,conn);
try
{
conn.Open();
DataSetds=newDataSet();
da.Fill(ds);
conn.Close();
returnds;
}
catch(Exceptione)
{
Response.Write("<script>window.alert("没有数据,或者"+e.Message+"")</script>");
returnnull;
}
}

以上是插入07以前版本excel

如果07版本以后只需要做小小修改
复制代码代码如下:

stringstrCon="Provider=Microsoft.ACE.OLEDB.12.0;DataSource="+lable+";ExtendedProperties=Excel12.0;";