Hi I have created one script which is taking Excel file and converting it to .txt files.But the code is not converting some of the excel files correctly. I dont know the reason, the reason might be different formats in one worksheet or some other issue. But the thing is if the format is coming differenty then also I want to handle the excel and each column should be generated in .txt files.Can anyone please help me regarding this problem as this is very urgent.
usingSystem;System.IO;
using
System.Data;using
System.Data.OleDb;using
System.Collections.Generic;using
System.ComponentModel;using
System.Text;using
System.Data.SqlClient;using
System.Windows.Forms;//using System.Threading;namespace
{
[System.AddIn.
ST_429b5e76bab24ae3a998c68118acd459.csprojAddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]publicpartialclassScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase{
#region
VSTA generated codeenumScriptResults{
Success = Microsoft.SqlServer.Dts.Runtime.
Failure = Microsoft.SqlServer.Dts.Runtime.
};
DTSExecResult.Success,DTSExecResult.Failure#endregion
The execution engine calls this method when the task executes.
To access the object model, use the Dts property. Connections, variables, events,
and logging features are available as members of the Dts property as shown in the following examples.
To reference a variable, call Dts.Variables["MyCaseSensitiveVariableName"].Value;
To post a log entry, call Dts.Log("This is my log text", 999, null);
To fire an event, call Dts.Events.FireInformation(99, "test", "hit the help message", "", 0, true);
To use the connections collection use something like the following:
ConnectionManager cm = Dts.Connections.Add("OLEDB");
cm.ConnectionString = "Data Source=localhost;Initial Catalog=AdventureWorks;Provider=SQLNCLI10;Integrated Security=SSPI;Auto Translate=False;";
Before returning from this method, set the value of Dts.TaskResult to indicate success or failure.
To open Help, press F1.
*/
/*
{
convertExcelToCSV();
publicvoid Main()// TODO: Add your code hereDts.TaskResult = (
}
{
connectionString = Dts.Variables[
connectionString = connectionString.Replace(
connectionString = connectionString.Replace(
cnn =
cnn.Open();
sql =
sqlComm.CommandType =
sqlComm.CommandTimeout = 0;
sqlCommdes.CommandTimeout = 0;
sqlADP.Fill(report);
sqlADPdes.Fill(reportdes);
sourceFile_CP = row[0].ToString();
Target_Directory_CP = rowdes[0].ToString();
cnn.Close();
int)ScriptResults.Success;privatevoid convertExcelToCSV()string worksheetName = String.Empty;string targetFile = String.Empty;string sourceFile_CP=null;string Target_Directory_CP=null;string lookupSheet = String.Empty;SqlConnection cnn;string connectionString = null;string sql = null;"User::v_ETL_MP_DQIMTD"].Value.ToString();"Provider=SQLNCLI10.1;", "");"Auto Translate=False", "");newSqlConnection(connectionString);"select ConfiguredValue from dbo.PackageConfigurationsLog_Source_To_PreStage_M where ConfigurationFilter='ExcelSrcPath'";string sqldes = "select ConfiguredValue from dbo.PackageConfigurationsLog_Source_To_PreStage_M where ConfigurationFilter='Destination_Directory'";SqlCommand sqlComm = newSqlCommand(sql, cnn);SqlCommand sqlCommdes = newSqlCommand(sqldes, cnn);CommandType.Text;SqlDataAdapter sqlADP = newSqlDataAdapter(sqlComm);SqlDataAdapter sqlADPdes = newSqlDataAdapter(sqlCommdes);DataSet report = newDataSet();DataSet reportdes = newDataSet();DataRow row = report.Tables[0].Rows[0];DataRow rowdes = reportdes.Tables[0].Rows[0];///**************For Reading Excel Source****
string strConn1 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + sourceFile_CP + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\""; OleDbConnection conn = null;StreamWriter wrtr = null;OleDbCommand cmd = null;OleDbDataAdapter da = null;try{
conn =
conn.Open();
sqlselect =
sqlselectComm.CommandType =
sqlselectComm.CommandTimeout = 0;
newOleDbConnection(strConn1);string sqlselect = null;"SELECT FileName FROM [ETL_MP_DQIMTD].[dbo].[FileName_ColumnName_M] where Data in ('CP') and FileName Not like '%ForecastSalesDomestic_%'";SqlCommand sqlselectComm = newSqlCommand(sqlselect, cnn);CommandType.Text;SqlDataAdapter sqlselectADP = newSqlDataAdapter(sqlselectComm);//DataSet report = new DataSet();
sqlselectADP.Fill(Tab);
{
{
lookupSheet = Row[
{
{
worksheetName = rows[
{
targetFile = Target_Directory_CP + Export_File_Name;
cmd =
cmd.CommandType =
wrtr =
da =
da.Fill(dt);
{
HdrString.Append(dt.Columns[y].ColumnName.ToString() +
}
wrtr.WriteLine(HdrString.ToString().Substring(0, HdrString.Length - 1));
{
{
rowString.Append((
DataTable Tab = newDataTable();if (Tab != null)foreach (DataRow Row in Tab.Rows)int v_IsFileExists = 0;Boolean the_fire_again = true;"FileName"].ToString();DataTable dtWS = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);if ((dtWS != null))foreach (DataRow rows in dtWS.Rows)"TABLE_NAME"].ToString().Replace("'", "");if (worksheetName.Contains(lookupSheet) && (worksheetName.EndsWith("$") == true))string Export_File_Name = rows["TABLE_NAME"].ToString().Replace(">", "").Replace("$", "").Replace("'", "").Trim() + ".txt";newOleDbCommand("SELECT * FROM [" + worksheetName + "]", conn);CommandType.Text;newStreamWriter(targetFile);newOleDbDataAdapter(cmd);DataTable dt = newDataTable();StringBuilder HdrString = newStringBuilder();for (int y = 0; y < dt.Columns.Count; y++)";");for (int x = 0; x < dt.Rows.Count; x++)StringBuilder rowString = newStringBuilder();for (int y = 0; y < dt.Columns.Count; y++)if (dt.Rows[x][y].ToString().Contains("e+"))Convert.ToDouble(dt.Rows[x][y])).ToString() + ";");elserowString.Append(dt.Rows[x][y].ToString() +
}
wrtr.WriteLine(rowString.ToString().Substring(0, rowString.Length - 1));
}
wrtr.Close();
wrtr.Dispose();
v_IsFileExists = 1;
}
}
}
{
Dts.Events.FireInformation(0,
";");if (v_IsFileExists != 1)string Filename = Row["FileName"].ToString();"FileName: ", Filename + " is not found", string.Empty, 0, ref the_fire_again);//MessageBox.Show(Filename+" "+"Does not Exist in the Sheet");}
}
}
}
{
}
catch (Exception exc)Console.WriteLine(exc.ToString());Console.ReadLine();finally{
conn.Close();
conn.Dispose();
cmd.Dispose();
da.Dispose();
}
}
}
}
if (conn.State == ConnectionState.Open)
using