一点点代码,上传xls,然后将它导入到数据库相应的表

protected void Click()
    {
        string postName=file1.PostedFile.FileName;
        if (postName == "")
        {
            Response.Write("<script>alert('请先选择文件.');location='add.aspx';</script>");
        }
        else
        {
            string str = this.UpLoadFile();
            if (str == "Error")
            {
                Response.Write("<script>alert('上传xls文件失败.');location='add.aspx';</script>");
            }
            else
            {
                string mystring = "Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source = "+str+";Extended Properties=Excel 8.0";
                OleDbConnection cnnxls = new OleDbConnection(mystring);
                OleDbDataAdapter myDa = new OleDbDataAdapter("select * from [Sheet1$]", cnnxls);
                DataSet myDs = new DataSet();
                myDa.Fill(myDs);
                if (myDs.Tables[0].Rows.Count > 0)
                {
                    string strSql = "";
                    string CnnString = "Provider=SQLOLEDB;database=testnews;server=(local);uid=sa;pwd=";
                    OleDbConnection conn = new OleDbConnection(CnnString);
                    conn.Open();
                    OleDbCommand myCmd = null;
                    for (int i = 0; i < myDs.Tables[0].Rows.Count; i++)
                    {
                        strSql = "insert into website(sname,surl) values ('";
                        strSql += myDs.Tables[0].Rows[i].ItemArray[0].ToString() + "', '";
                        strSql += myDs.Tables[0].Rows[i].ItemArray[1].ToString() + "')";
                        try
                        {
                            myCmd = new OleDbCommand(strSql, conn);
                            myCmd.ExecuteNonQuery();
                            Response.Write("<script language=javascript>alert('数据导入成功.');location='index.aspx';</script>");
                        }
                        catch
                        {
                            Response.Write("<script language=javascript>alert('数据导入失败.');location='add.aspx';</script>");
                        }
                    }
                }
             }
        }

相关文章:

  • 2021-12-06
  • 2022-01-01
  • 2021-12-22
  • 2021-12-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-18
猜你喜欢
  • 2021-09-28
  • 2021-12-20
  • 2022-12-23
  • 2021-11-20
  • 2021-08-16
  • 2022-01-08
相关资源
相似解决方案