初步认识asp.net中导入excell

来源:互联网 发布:在淘宝买到假货怎么办 编辑:程序博客网 时间:2024/05/22 07:51

2012年12月8日。初次接触把excell中的数据导入数据库,做个笔记吧。以备忘了只需。

  protected void btnRead_Click(object sender, EventArgs e)
        {
            if (this .fulChoose .HasFile )//如果fileupload控件里面有文件
            {
                string fileExtension = System.IO.Path.GetExtension(this .fulChoose .PostedFile .FileName );//获得文件的扩展名
                if (fileExtension .ToLower ()==".xls")
                {
                    string serverPath = Server.MapPath("UploadExcells");
                    if (!System .IO .Directory .Exists (serverPath ))
                    {
                        System.IO.Directory.CreateDirectory(serverPath);
                    }
                    string newPath = serverPath + "\\" + this.fulChoose.FileName;

                    this.fulChoose.SaveAs(newPath );//保存该文件
                    DataSet ds = new DataSet();
                    OleDbConnection con = new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=\"Excel 8.0;\";Data Source={0};", newPath  ));
                    OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [xixi$A:T]", con);
                    OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
                    cb.QuotePrefix = "[";
                    cb.QuoteSuffix = "]";
                    try
                    {
                        con.Open();
                        da.Fill(ds, 0, 0, "[heihei$]");
                    }
                    catch (Exception)
                    {

                        throw;
                    }
                    finally { con.Close(); }
                    if (ds.Tables [0]!=null )
                    {
                        for (int i = 0; i < ds.Tables [0].Rows .Count ; i++)
                        {
                            DataRow r = ds.Tables[0].Rows[i];
                            string m = r[0].ToString();
                        }
                    }
                }
                else
                {
                    this.ClientScript.RegisterStartupScript(Page.GetType(), "hello", "<script>alert('请选择.xls格式的文件!');</script>");
                }
            }
            else
            {
                this.ClientScript.RegisterStartupScript(Page.GetType(), "hello", "<script>alert('请选择要阅读的文件');</script>");
            }
        }
    }