首页 文章

如何在ssis中加载多张excel(2016)文件

提问于
浏览
0

这段代码完全适用于我的机器(我有excel 2010),但当我的主管试图运行但不能在他的机器上工作时(他有excel 2016)所以对于excel 2016我需要更改连接ConStr =“Provider = Microsoft.ACE .OLEDB.12.0;数据源=“fileFullPath”;扩展属性= \“Excel 12.0; HDR =”HDR“; IMEX = 0 \”“; ??

string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
        string TableName = Dts.Variables["User::TableName"].Value.ToString();
        string SchemaName = Dts.Variables["User::SchemaName"].Value.ToString();
        string SheetNameToLoad = Dts.Variables["User::SheetNameLike"].Value.ToString();

        var directory = new DirectoryInfo(FolderPath);
        FileInfo[] files = directory.GetFiles();

        //Declare and initilize variables
        string fileFullPath = "";


        SqlConnection myADONETConnection = new SqlConnection();
        myADONETConnection = (SqlConnection)(Dts.Connections["DBconnection"].AcquireConnection(Dts.Transaction) as SqlConnection);

        ////Get one Book(Excel file at a time)
        foreach (FileInfo file in files)
        {
            fileFullPath = FolderPath + "\\" + file.Name;
            MessageBox.Show(fileFullPath);

            //    //Create Excel Connection
            string ConStr;
            string HDR;
            HDR = "YES";
            ConStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath + ";Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
            OleDbConnection cnn = new OleDbConnection(ConStr);

        //    //Get Sheet Name
            cnn.Open();
            DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

            string sheetname;
            sheetname = "";
            //Only read data from provided SheetNumber

            foreach (DataRow drSheet in dtSheet.Rows)
            {



                sheetname = drSheet["TABLE_NAME"].ToString();
                MessageBox.Show(sheetname);

                //Load the Data if Sheet Name contains value of SheetNameLike 
                if (sheetname.Contains(SheetNameToLoad) == true)
                {



                    //Load the DataTable with Sheet Data so we can get the column header
                    OleDbCommand oconn = new OleDbCommand("select  * from [" + sheetname + "] where CityName ='ARLINGTON'", cnn);
                    OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
                    DataTable dt = new DataTable();
                    adp.Fill(dt);
                    cnn.Close();



                    //Load Data from DataTable to SQL Server Table.
                    using (SqlBulkCopy BC = new SqlBulkCopy(myADONETConnection))
                    {
                        BC.DestinationTableName = SchemaName + "." + TableName;

                        BC.WriteToServer(dt);
                    }

                }
            }

1 回答

相关问题