使用asp.net

时间:2016-07-05 09:29:43

标签: asp.net sql-server excel temp-tables

为此开发Asp.Net将从Excel工作表中提取数据然后将其插入存储过程,在我的搜索期间知道它不可能,我可以将数据从excel表复制到临时表然后从临时表复制到临时表存储过程 这里是我用于将数据插入常规表的代码,请帮助

public partial class WebForm1 : System.Web.UI.Page
{

    OleDbConnection Econ;
    SqlConnection con;

    string constr, Query, sqlconn;

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    private void ExcelConn(string FilePath)
    {

        constr = string.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""", FilePath);
        Econ = new OleDbConnection(constr);

    }

    private void connection()
    {
        sqlconn = ConfigurationManager.ConnectionStrings["InvoiceProjectConnectionString"].ConnectionString;
        con = new SqlConnection(sqlconn);

    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
        InsertExcelRecords(CurrentFilePath);

    }

    private void InsertExcelRecords(string FilePath)
    {
        ExcelConn(FilePath);

        Query = string.Format("Select [CODE],[Brand],[SubBrand],[SubBrand2],[Category],[Category2] FROM [{0}]", "Sheet1$");

        OleDbCommand Ecom = new OleDbCommand(Query, Econ);
        Econ.Open();

        DataSet ds = new DataSet();
        OleDbDataAdapter oda = new OleDbDataAdapter(Query, Econ);
        Econ.Close();
        oda.Fill(ds);
        DataTable Exceldt = ds.Tables[0];
        connection();
        //creating object of SqlBulkCopy    
        SqlBulkCopy objbulk = new SqlBulkCopy(con);
        //assigning Destination table name    
        objbulk.DestinationTableName = "tblTest";
        //Mapping Table column    
        objbulk.ColumnMappings.Add("CODE", "Code");
        objbulk.ColumnMappings.Add("Brand", "Brand");
        objbulk.ColumnMappings.Add("SubBrand", "SubBrandOne");
        objbulk.ColumnMappings.Add("SubBrand2", "SubBrandTwo");
        objbulk.ColumnMappings.Add("Category", "Category");
        objbulk.ColumnMappings.Add("Category2", "CategoryTwo");

        //inserting Datatable Records to DataBase    
        con.Open();
        objbulk.WriteToServer(Exceldt);
        con.Close();
    }

}

1 个答案:

答案 0 :(得分:0)

您的代码没问题,但不完整......

    protected void Button1_Click(object sender, EventArgs e)
        {
            string CurrentFilePath = Path.GetFullPath(FileUpload1.PostedFile.FileName);
            //step 1...            
            InsertExcelRecords(CurrentFilePath);

            //step 2: execute your procedure on sql-server that read your temp-table "tblTest" and insert on your table
            PopulateTable();

        }

         protected void PopulateTable(){
         //Your code for execute your procedure...
        }

在sql-server上执行过程的示例:How to execute a stored procedure within C# program