//=============================
//查看Excel 数据
private void btnCheckExcle_Click(object sender, System.EventArgs e)
{
if (File1.PostedFile!=null)
{
//1. 保存于服务器,磁盘 ; 获取绝对路径
string fullFileName = File1.PostedFile.FileName;
string fileName = fullFileName.Substring(fullFileName.LastIndexOf("//") + 1);
fileName = DateTime.Now.Date.ToString("yyyymmdd") +fileName;
string theFilePath = @Server.MapPath("excelFiles/") + fileName;
File1.PostedFile.SaveAs(theFilePath);
//2. 获取Excel中的,表名
ArrayList al = ExcelSheetName(theFilePath);
string sheetName = (string)al[0];
//2. 导入到DataSet中
DataSet ds = this.ExcelDataSource(theFilePath,sheetName);
this.dgShow.DataKeyField = "No";
this.dgShow.DataSource = ds;
this.dgShow.DataBind();
}
}
//-----------------------------------------
//该方法实现从Excel中导出数据到DataSet中,其中filepath为Excel文件的绝对路径,sheetname为表示那个Excel表;
public DataSet ExcelDataSource( string filepath , string sheetname )
{
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
string strSql = string.Format(@"select * from [{0}]",sheetname);
OleDbDataAdapter oada = new OleDbDataAdapter(strSql,strConn);
DataSet ds = new DataSet ();
oada.Fill(ds);
return ds ;
}
//获得Excel中的所有sheetname。 filepath 为绝对路径
public ArrayList ExcelSheetName ( string filepath )
{
ArrayList al = new ArrayList ();
string strConn;
strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open ();
DataTable sheetNames = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables,new object[]{null,null,null,"TABLE"});
conn.Close ();
foreach ( DataRow dr in sheetNames.Rows )
{
al.Add ( dr[2] );
}
return al;
}
//-------------------
本文介绍了一种将Excel文件上传并解析至DataSet的方法。通过使用OLE DB连接读取Excel文件内容,实现表单数据的展示。同时提供了获取Excel中所有工作表名称的功能。
2554

被折叠的 条评论
为什么被折叠?



