Excel导入Sql

来源:互联网 发布:免费网吧计费软件 编辑:程序博客网 时间:2024/04/28 19:07

protected void Button1_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string ExtensionName = System.IO.Path.GetExtension(FileUpload1.PostedFile.FileName).ToLower();
            //if (FileUpload1.PostedFile.ContentType == "application/vnd.ms-excel")
            if(ExtensionName==".xls")
            {               
                Session["count"] = 0;
                Label3.Text = "Excel文件为:" + FileUpload1.PostedFile.FileName;
                HiddenField1.Value = "T";
                Label2.Text = "";
                Data();
            }
            else
            {
                this.ClientScript.RegisterClientScriptBlock(this.GetType(), "MESSAGE", "alert('类型不正确,必须为Excel文件');", true);
            }
        }
        else
        {
            this.ClientScript.RegisterClientScriptBlock(this.GetType(), "MESSAGE", "alert('请先选择要导入的文件');", true);
        }
    }

===================================================================================
public void Data()
    {
        HiddenField1.Value = DateTime.Now.ToString();
        string path = FileUpload1.PostedFile.FileName;
        string conStr = string.Format("Provider=Microsoft.Jet.OLEDB.4.0;data source={0};Extended Properties=Excel 8.0;", path);
        OleDbConnection con = new OleDbConnection(conStr);
        con.Open();
        //读取Excel表结构,把表包含的所有Sheet存入Sheets[]数组中
        DataTable schemaTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string[] Sheets = new string[schemaTable.Rows.Count];
        int i = 0;
        foreach (DataRow dr in schemaTable.Rows)
        {
            Sheets[i] = dr["TABLE_NAME"].ToString();
            i++;
        }
        //测试,导入第一个Sheet$
        int j = Convert.ToInt32(Session["count"].ToString());
        string strSheet1 = "select * from [" + Sheets[j].ToString() + "]";
        OleDbDataAdapter da = new OleDbDataAdapter(strSheet1, con);
        DataSet ds = new DataSet();
        da.Fill(ds, "EX");
        string strConn = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ITDB"].ConnectionString;
        SqlConnection Sqlcon = new SqlConnection(strConn);
        if (Sqlcon.State == ConnectionState.Closed)
        {
            Sqlcon.Open();
        }          
        SqlBulkCopy excelCopy = new SqlBulkCopy(strConn,SqlBulkCopyOptions.UseInternalTransaction);
        excelCopy.BatchSize = 100;
        excelCopy.BulkCopyTimeout = 60;
        excelCopy.SqlRowsCopied +=new SqlRowsCopiedEventHandler(excelCopy_SqlRowsCopied);
        excelCopy.NotifyAfter = ds.Tables["EX"].Rows.Count;
        //excelCopy.ColumnMappings.Add("srcid","descID");
        try
        {
            excelCopy.DestinationTableName = "dbo.ExcelTest";
            excelCopy.WriteToServer(ds.Tables["EX"]);
            Label2.Text = "导入成功";
        }
        catch (Exception ex)
        {
            this.Label2.Text = "测试时发生错误:" + ex.Message.ToString();
        }
        finally
        {
            Sqlcon.Close();
            con.Close();
        }
===================================================================================
private void excelCopy_SqlRowsCopied(object sender, SqlRowsCopiedEventArgs args)
    {
        Label7.Text += args.RowsCopied.ToString() + "条数据被导入/r/n";
        TimeSpan copyTime = DateTime.Now - DateTime.Parse(HiddenField1.Value);
        Label7.Text += "导入时间为:" + copyTime.Seconds.ToString() + "." + copyTime.Milliseconds.ToString() + "秒";
    }