项目中经常会用到把Excel的文件内容导入到数据库中的,刚刚花了点时间,做了个例子,基本上能实现导入Excel后显示的功能吧,导入的excel文件得是xls,即是2003的.
代码思路如下:要读取的excel文件必得得是在本地硬盘,所以一般来说都是让远程用户选择自己硬盘上的Excel文件,然后把用户选择的文件上传到本地服务器上,再在本地服务器上进行操作.我把界面后置代码重要部分贴出来,大家自己慢慢看吧,都有注释了.
- PRotected void 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();
- }
-
-
- private bool 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, new object[] { null, null, null, "TABLE" });
- conn.Close();
- foreach (DataRow dr in sheetNames.Rows)
- {
- al.Add(dr[2]);
- }
- return al;
- }
要注意的是我们要一开始就在网站根目录下建立upload文件夹,而且要把他的权限设置为可读可写的?这个权限的问题搞得头大,不知道到底应该怎么搞的,XP系统下新建立的文件夹好像都是只读的,我右键属性把只读去掉,结果再次查看的时候还是只读,不过好像发现对程序没有什么意思,上传完excel文件后还是可以读取查看的.