---------------
protected void btnUpload_Click(object sender, EventArgs e)//上传文件
{
if (FileUpload1.HasFile)
{
//try
//{
string path = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString()) + "xls\\";//获取程序根目录
path += Path.GetFileName(FileUpload1.FileName);
FileUpload1.PostedFile.SaveAs(path);
// BindGrid(lblCurrentPath.Text);
//string xlsPath = path; // 绝对物理路径
string dbName=Path.GetFileName(FileUpload1.FileName).Replace("xls","");
// 查询语句
string xlsPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "xls\\" + Path.GetFileName(FileUpload1.FileName);
this.GvData.DataSource = GetExcelContent(xlsPath, dbName);
this.GvData.DataBind();
//}
//catch
//{
//ClientScript.RegisterStartupScript(typeof(Page), "aa", "alert('文件上传失败!')", true);
//}
}
}
private DataSet GetExcelContent(string filepath, string dbName)
{
string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties='Excel 8.0;HDR=No;IMEX=1'";
System.Data.OleDb.OleDbConnection myConn = new System.Data.OleDb.OleDbConnection(strCon);
string strCom = "SELECT * FROM [" + dbName + "$]";
myConn.Open();
System.Data.OleDb.OleDbDataAdapter myCommand = new System.Data.OleDb.OleDbDataAdapter(strCom, myConn);
//创建一个DataSet对象
DataSet myDataSet = new DataSet();
//得到自己的DataSet对象
myCommand.Fill(myDataSet);
//关闭此数据链接
myConn.Close();
return myDataSet;
}
另外,站长团上有产品团购,便宜有保证
//查询全部
public DataSet SelectPhone()
{
SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=DB;User ID=sa;pwd=sa");
DataSet ds = new DataSet();
string sql1 = "select id as '编号',user_phone as '手机号码',user_name as '姓名' from TelCode";
SqlDataAdapter sda = new SqlDataAdapter(sql1, conn);
sda.Fill(ds, "phone");
return ds;
}
private void Form1_Load(object sender, EventArgs e)
{
//显示查询出来的信息
dvAll.DataSource = SelectPhone().Tables["phone"];
}
我写过这样一个类似的代码,你看一下是否对你有帮助