使用 asp.net 将 Excel sheet 数据插入 sql 服务器中的存储过程

Inserting Excel sheet data into a stored procedure in sql server using asp.net

为此开发 Asp.Net 将从 excel sheet 中提取数据,然后将其插入存储过程,在我的搜索过程中知道这是不可能的,我可能会从excel sheet 到临时 table 然后从临时 table 到存储过程 这是我用于将数据插入常规 table 背后的代码,请帮忙

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();
    }

}

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

    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 服务器上执行程序的示例:How to execute a stored procedure within C# program