ASP.net中读取excel内容,并显示在界面上
来源:互联网 发布:2020年中国 知乎 编辑:程序博客网 时间:2024/05/22 11:38
-
- protectedvoid btnUp_Click(object sender, EventArgs e)
- {
- bool b = Upload(fuExcel);
- if (!b)
- {
- return;
- }
- string name = fuExcel.FileName;
- string filepath = Server.MapPath("~/upload/") + name;
- DataSet ds = ExcelDataSource(filepath, ExcelSheetName(filepath)[0].ToString());
- GridView1.DataSource = ds;
- GridView1.DataBind();
- }
-
-
- privatebool Upload(FileUpload myFileUpload)
- {
- bool flag =false;
-
- bool fileAllow =false;
-
- string[] allowExtensions = {".xls" };
-
-
- string path = HttpContext.Current.Request.MapPath("~/upload/");
-
- if (myFileUpload.HasFile)
- {
-
- string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower();
-
- for (int i = 0; i < allowExtensions.Length; i++)
- {
- if (fileExtension == allowExtensions[i])
- {
- fileAllow = true;
- }
- }
-
- if (fileAllow)
- {
- try
- {
-
- myFileUpload.SaveAs(path + myFileUpload.FileName);
- lblMes.Text = "文件导入成功";
- flag = true;
- }
- catch (Exception ex)
- {
- lblMes.Text += ex.Message;
- flag = false;
- }
- }
- else
- {
- lblMes.Text = "不允许上载:" + myFileUpload.PostedFile.FileName +",只能上传xls的文件,请检查!";
- flag = false;
- }
- }
- else
- {
- lblMes.Text = "请选择要导入的excel文件!";
- flag = false;
- }
- return flag;
- }
-
-
- 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);
- OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "]", strConn);
- DataSet ds = new DataSet();
- oada.Fill(ds);
- conn.Close();
- return ds;
- }
-
-
- 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, newobject[] {null,null,null,"TABLE" });
- conn.Close();
- foreach (DataRow drin sheetNames.Rows)
- {
- al.Add(dr[2]);
- }
- return al;
- }