C#在SSIS Visual Studio Excel工作表名称中导入,带空格

时间:2018-12-14 15:48:34

标签: c# excel visual-studio ssis

在读取excel工作表时,工作表名称中带有空格的人在执行脚本时会抛出错误。

解决方案似乎在此select * from [" + sheetname + "]"中。但是,当删除括号或将双引号替换为简单引号时,没有一个示例能够给出正确的解决方案。

sheetname.replace(“”,“ _”)是我看到的能够选择带有空格的图纸的唯一方法吗?

PS:当我删除源文件中的空格并将其替换为“ _”时,脚本运行良好。但不幸的是,我无法手动执行此操作。

谢谢

> OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);

这是我在Visual Studio中拥有的全部代码。

  namespace ST_689a7e5f91cd44f892e3d4b3290d003b
    {
            public void Main()
            {
                // TODO: Add your code here
                String FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
                var directory = new DirectoryInfo(FolderPath);
                FileInfo[] files = directory.GetFiles();

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

            //Get one Book(Excel file at a time)
            foreach (FileInfo file in files)
            {
                string filename = "";
                fileFullPath = FolderPath + "\\" + file.Name;
                filename = file.Name.Replace(".xlsx", "");
                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=1\"";
                OleDbConnection cnn = new OleDbConnection(ConStr);


                //Get Sheet Name
                cnn.Open();
                DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                string sheetname;
                sheetname = "";
                foreach (DataRow drSheet in dtSheet.Rows)
                {
                    if (drSheet["TABLE_NAME"].ToString().Contains("$"))
                    {


                        sheetname = drSheet["TABLE_NAME"].ToString();
                        //Display Sheet Name , you can comment it out
                        MessageBox.Show(sheetname);



                        //Load the DataTable with Sheet Data  sheetname =  Regex.Replace(input, @"[^0-9a-zA-Z\._]", string.Empty);
                        OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
                        //cnn.Open();
                        OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
                        DataTable dt = new DataTable();
                        adp.Fill(dt);

                        //drop $from sheet name
                        sheetname = sheetname.Replace("$", "");


                        // Generate Create Table Script by using Header Column,It will drop the table if Exists and Recreate                  
                        string tableDDL = "";
                        tableDDL += "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = ";
                        tableDDL += "OBJECT_ID(N'[dbo].[" + filename + "_" + sheetname + "]') AND type in (N'U'))";
                        tableDDL += "Drop Table [dbo].[" + filename + "_" + sheetname + "]";
                        tableDDL += "Create table [" + filename + "_" + sheetname + "]";
                        tableDDL += "(";
                        for (int i = 0; i < dt.Columns.Count; i++)
                        {
                            if (i != dt.Columns.Count - 1)
                                tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)" + ",";
                            else
                                tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)";
                        }
                        tableDDL += ")";


                        //use ADO.NET connection to Create Table from above Definition
                        SqlConnection myADONETConnection = new SqlConnection();
                        myADONETConnection = (SqlConnection)(Dts.Connections["DBConn"].AcquireConnection(Dts.Transaction) as SqlConnection);
                        //you can comment the messagebox, it is for debugging
                        MessageBox.Show(tableDDL.ToString());
                        SqlCommand myCommand = new SqlCommand(tableDDL, myADONETConnection);
                        myCommand.ExecuteNonQuery();
                        //Comment this message, it is for debugging
                        MessageBox.Show("TABLE IS CREATED");


                        //Load the data from DataTable to SQL Server Table.
                        SqlBulkCopy blk = new SqlBulkCopy(myADONETConnection);
                        blk.DestinationTableName = "[" + filename + "_" + sheetname + "]";
                        blk.WriteToServer(dt);
                    }
                }
            }


            Dts.TaskResult = (int)ScriptResults.Success;
        }

        #region ScriptResults declaration
        /// <summary>
        /// This enum provides a convenient shorthand within the scope of this class for setting the
        /// result of the script.
        /// 
        /// This code was generated automatically.
        /// </summary>
        enum ScriptResults
        {
            Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
            Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
        };
        #endregion

    }
}

0 个答案:

没有答案