现我们来看看代码:
protected void Button1_Click(object sender, EventArgs e)//读取按钮事件
{
this.GridView1.DataSource = CreateDataSource();
this.GridView1.DataBind();
}
private DataSet CreateDataSource()
{
string strCon;
//用excel作为数据源 ,Server.MapPath("Book1.xls")中这个Book1.xls文件已经在服务器内,且目录与当前cs文件目录相同
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Book1.xls") + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strCon);
OleDbDataAdapter myda = new OleDbDataAdapter("select * from [Sheet1$]", strCon);
DataSet myds = new DataSet();
myda.Fill(myds);
return myds;
}
{
this.GridView1.DataSource = CreateDataSource();
this.GridView1.DataBind();
}
private DataSet CreateDataSource()
{
string strCon;
//用excel作为数据源 ,Server.MapPath("Book1.xls")中这个Book1.xls文件已经在服务器内,且目录与当前cs文件目录相同
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("Book1.xls") + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strCon);
OleDbDataAdapter myda = new OleDbDataAdapter("select * from [Sheet1$]", strCon);
DataSet myds = new DataSet();
myda.Fill(myds);
return myds;
}
在实际应用中,我们可以用一个上传控件,把用户要显示的xls读取到服务器文件夹内,然再将它读到GridView中。
PS:上例中的Server.MapPath("")是用来读取服务器中的xls文件,如果文件不在服务器中也是能读到的,比如就在
用户的本地磁盘也行,代码可作如下改动:
private DataSet CreateDataSource()
{
string filePath = "";
if (FJ.PostedFile.FileName == "")
{
Response.Write("<script language=javascript>alert('请选择要上传的文件!');</script>");
return null;
}
else
{
filePath = FJ.PostedFile.FileName;//取得文件路径
string strCon;
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +filePath+ ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strCon);
OleDbDataAdapter myda = new OleDbDataAdapter("select * from [Sheet1$]", strCon);
DataSet myds = new DataSet();
myda.Fill(myds);
return myds;
}
}
{
string filePath = "";
if (FJ.PostedFile.FileName == "")
{
Response.Write("<script language=javascript>alert('请选择要上传的文件!');</script>");
return null;
}
else
{
filePath = FJ.PostedFile.FileName;//取得文件路径
string strCon;
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +filePath+ ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strCon);
OleDbDataAdapter myda = new OleDbDataAdapter("select * from [Sheet1$]", strCon);
DataSet myds = new DataSet();
myda.Fill(myds);
return myds;
}
}
filePath 就直接是用户本地磁盘上的路径了。操作完成后,服务器中并没有这个xls文件。
还有就是如果要将数据再读入到数据库中就可以去操作那个dataset了,因为数据是先读到dst中的,可以去读取dst中表的每条记录,
然后再插入到数据库中保存.