Как использовать задачу скрипта или компонент преобразования скрипта, чтобы разделить данные буфера на несколько вкладок одного файла Excel и загрузить их - PullRequest
0 голосов
/ 09 ноября 2019

Я пытаюсь разделить данные буфера на различные вкладки файла Excel. Таким образом, буферные данные содержат данные о сотрудниках компании, где одно из полей / столбцов - «Город», я хотел бы, чтобы в нем были отдельные вкладки для каждого города и информация о сотрудниках, которые живут в этом городе. Таким образом, во вкладке «Excel» в Бостоне все сотрудники будут жить в Бостоне. Столбец «Город» может иметь любое количество городов, поэтому это динамическое поле.

Подход, который я хочу использовать, заключается в том, чтобы сначала все перебрать значения в столбце «Город» и сохранить уникальные значения в массиве. Как мне это сделать в C #? Как только мы получим уникальные значения, снова проходим по данным и сохраняем строки в соответствующих ссылках. Это данные, которые есть в моем буфере (источнике).

И данные, которые я хочу получить, представляют собой файл Excel с данными о сотрудниках каждого города

Итак, я создал задачу сценария для удовлетворения моих требований. Проблема с моим кодом C # заключается в его пропуске после кода в строке 103, который имеет вид dt.Load (cmd.ExecuteReader ());и выполнение блока catch. Я исследовал, почему это так, но не получил никаких конкретных ответов и ответов, я попытался найти и устранить неисправность, поставив передовые точки и пройдя через это, но ничто не указывает мне на проблемы. Я новичок в C #, поэтому любые указатели будут с благодарностью. Я открыт без разрешения кода C # тоже, если есть. Вот код C #

    #region Help:  Introduction to the script task
/* The Script Task allows you to perform virtually any operation that can be accomplished in
 * a .Net application within the context of an Integration Services control flow. 
 * 
 * Expand the other regions which have "Help" prefixes for examples of specific ways to use
 * Integration Services features within this script task. */
#endregion


#region Namespaces
using System;
using System.Data;
using Microsoft.SqlServer.Dts.Runtime;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.IO;
#endregion

namespace ST_31ec630ee01447a8b688790e58f06464
{

    [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute]
    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase
    {
        #region Help:  Using Integration Services variables and parameters in a script
        /* To use a variable in this script, first ensure that the variable has been added to 
         * either the list contained in the ReadOnlyVariables property or the list contained in 
         * the ReadWriteVariables property of this script task, according to whether or not your
         * code needs to write to the variable.  To add the variable, save this script, close this instance of
         * Visual Studio, and update the ReadOnlyVariables and 
         * ReadWriteVariables properties in the Script Transformation Editor window.
         * To use a parameter in this script, follow the same steps. Parameters are always read-only.
         * 
         * Example of reading from a variable:
         *  DateTime startTime = (DateTime) Dts.Variables["System::StartTime"].Value;
         * 
         * Example of writing to a variable:
         *  Dts.Variables["User::myStringVariable"].Value = "new value";
         * 
         * Example of reading from a package parameter:
         *  int batchId = (int) Dts.Variables["$Package::batchId"].Value;
         *  
         * Example of reading from a project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].Value;
         * 
         * Example of reading from a sensitive project parameter:
         *  int batchId = (int) Dts.Variables["$Project::batchId"].GetSensitiveValue();
         * */

        #endregion

        #region Help:  Firing Integration Services events from a script
        /* This script task can fire events for logging purposes.
         * 
         * Example of firing an error event:
         *  Dts.Events.FireError(18, "Process Values", "Bad value", "", 0);
         * 
         * Example of firing an information event:
         *  Dts.Events.FireInformation(3, "Process Values", "Processing has started", "", 0, ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14, "Process Values", "No values received for input", "", 0);
         * */
        #endregion

        #region Help:  Using Integration Services connection managers in a script
        /* Some types of connection managers can be used in this script task.  See the topic 
         * "Working with Connection Managers Programatically" for details.
         * 
         * Example of using an ADO.Net connection manager:
         *  object rawConnection = Dts.Connections["Sales DB"].AcquireConnection(Dts.Transaction);
         *  SqlConnection myADONETConnection = (SqlConnection)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Sales DB"].ReleaseConnection(rawConnection);
         *
         * Example of using a File connection manager
         *  object rawConnection = Dts.Connections["Prices.zip"].AcquireConnection(Dts.Transaction);
         *  string filePath = (string)rawConnection;
         *  //Use the connection in some code here, then release the connection
         *  Dts.Connections["Prices.zip"].ReleaseConnection(rawConnection);
         * */
        #endregion



        public void Main()
        {
            try
            {
                string accountquery = Dts.Variables["User::account_query"].Value.ToString();

                //USE ADO.NET Connection from SSIS Package to get data from table
                SqlConnection myADONETConnection = new SqlConnection();
                myADONETConnection = (SqlConnection)(Dts.Connections["ODSDEV"].AcquireConnection(Dts.Transaction) as SqlConnection);
                //MessageBox.Show(myADONETConnection);
                myADONETConnection.Open();
                SqlCommand cmd = new SqlCommand(accountquery, myADONETConnection);

                //MessageBox.Show(accountquery);
                //Saving unique accounts into "dt" DataTable
                DataTable dt = new DataTable();
                dt.Load(cmd.ExecuteReader());
                MessageBox.Show("hello");
                myADONETConnection.Close();

                //start for main for each, this loops through all trilogie logons
                foreach (DataRow dt_row in dt.Rows)
                {
                    string ColumnValue = "";
                    object[] array = dt_row.ItemArray;
                    ColumnValue = array[0].ToString();

                    //Load Data into DataTable from SQL ServerTable
                    string queryString = Dts.Variables["User::account_query"].Value.ToString() + ColumnValue + "'";
                    SqlDataAdapter adapter = new SqlDataAdapter(queryString, myADONETConnection);
                    DataSet ds = new DataSet();
                    adapter.Fill(ds);

                    //Get Header Columns
                    string TableColumns = "";

                    // Get the Column List from Data Table so can create Excel Sheet with Header
                    foreach (DataTable table in ds.Tables)
                    {
                        foreach (DataColumn column in table.Columns)
                        {
                            TableColumns += column + "],[";
                        }
                    }

                    // Replace most right comma from Columnlist
                    TableColumns = ("[" + TableColumns.Replace(",", " Text,").TrimEnd(','));
                    TableColumns = TableColumns.Remove(TableColumns.Length - 2);
                    //MessageBox.Show(TableColumns);


                    //Use OLE DB Connection and Create Excel Sheet
                    OleDbConnection Excel_OLE_Con = new OleDbConnection();
                    string ExcelFileName = Dts.Variables["User::ExcelFileName"].Value.ToString();
                    string FolderPath = Dts.Variables["User::FolderPath"].Value.ToString();
                    //Construct ConnectionString for Excel
                    string connstring = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
                        + ";" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
                    Excel_OLE_Con.ConnectionString = connstring;
                    Excel_OLE_Con.Open();

                    OleDbCommand Excel_OLE_Cmd = new OleDbCommand();
                    Excel_OLE_Cmd.Connection = Excel_OLE_Con;
                    Excel_OLE_Cmd.CommandText = "Create table [" + ColumnValue + "] (" + TableColumns + ")";
                    Excel_OLE_Cmd.ExecuteNonQuery();

                    //Write Data to Excel Sheet from DataTable dynamically
                    foreach (DataTable table in ds.Tables)
                    {
                        String sqlCommandInsert = "";
                        String sqlCommandValue = "";
                        foreach (DataColumn dataColumn in table.Columns)
                        {
                            sqlCommandValue += dataColumn + "],[";
                        }

                        sqlCommandValue = "[" + sqlCommandValue.TrimEnd(',');
                        sqlCommandValue = sqlCommandValue.Remove(sqlCommandValue.Length - 2);
                        sqlCommandInsert = "INSERT into [" + ColumnValue + "] (" + sqlCommandValue + ") VALUES(";

                        int columnCount = table.Columns.Count;
                        foreach (DataRow row in table.Rows)
                        {
                            string columnvalues = "";
                            for (int i = 0; i < columnCount; i++)
                            {
                                int index = table.Rows.IndexOf(row);
                                columnvalues += "'" + table.Rows[index].ItemArray[i] + "',";

                            }
                            columnvalues = columnvalues.TrimEnd(',');
                            var command = sqlCommandInsert + columnvalues + ")";
                            Excel_OLE_Cmd.CommandText = command;
                            Excel_OLE_Cmd.ExecuteNonQuery();
                        }

                    }
                    Excel_OLE_Con.Close();
                }//end of main for each
               Dts.TaskResult = (int)ScriptResults.Success;
            }//end of try block
            catch (Exception badscript)
            {
                MessageBox.Show("something messed up!");
            }

        }

        #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

    }
}
...