网上转载……
//上传文件
string filename = FileUpload1.FileName;
string path = Server.MapPath("c:\\123\\" + filename);
FileUpload1.SaveAs(path);
string strConn = GetExcelConnString(path);
OleDbConnection conn = new OleDbConnection(strConn);
try
{
conn.Open();
}
catch (Exception ex)
{
//ShowClientJS("ShowInfo(\"错误:" + ex.Message + "\",1,5000);", this);
return;
}
//判断工作表个数
DataTable dtTblNames = conn.GetSchema("Tables");
if (dtTblNames.Rows.Count > 1)
{
conn.Close();
//ShowClientJS("ShowInfo('导入失败:只允许1个工作表,当前有:" + dtTblNames.Rows.Count.ToString() + "',1,5000);", this);
return;
}
//只处理第一个工作表
string tblName = dtTblNames.Rows[0]["Table_Name"].ToString();
hidTableName.Value = tblName;
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "select * from [" + tblName + "]";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataTable dt = new DataTable();
try
{
da.Fill(dt);
}
catch (Exception ex)
{
//ShowClientJS("ShowInfo(\"预览时发生错误:" + ex.Message + "\",1,5000);", this);
}
finally
{
conn.Close();
}
//显示数据
GridView1.DataSource = dt;
GridView1.DataBind();