如何使用脚本任务或脚本转换组件将缓冲区数据分为同一Excel文件的多个选项卡并下载

我正在尝试将缓冲区数据划分为excel文件的各个选项卡。因此,缓冲数据具有公司的雇员数据,其中一个字段/列是“城市”,我希望每个城市都有单独的选项卡,以及该城市中居住的雇员的雇员信息。因此,excel选项卡“波士顿”将让所有员工都住在波士顿。 “城市”列可以包含任意数量的城市,因此这是一个动态字段。

我要采取的方法是首先全部遍历“城市”(City)列中的值,然后将唯一值保存到数组中。如何在C#中执行此操作?一旦获得唯一值,就再次遍历数据并将行保存到其相应​​的引用中。 This is the data that my buffer (source) has.

And the data I want to get is an excel file with employee data of each city

因此,我创建了一个脚本任务来满足我的要求。我的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,"Processing has started",ref fireAgain)
         * 
         * Example of firing a warning event:
         *  Dts.Events.FireWarning(14,"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

    }
}
snailtoto 回答:如何使用脚本任务或脚本转换组件将缓冲区数据分为同一Excel文件的多个选项卡并下载

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3135031.html

大家都在问