ssis script task add filename and sheetname to the table

Dinesh Kalva 100 Reputation points
2023-08-19T05:43:49.6933333+00:00

Hi, I'm using sqlbulkcopy dumping data into table. I want to add filename, sheetname to the table. Filename and sheetname fields are located last in the table. Below is my code.

FileInfo[] files = directory.GetFiles("*.*, SearchOption.AllDirectories);

foreach (FileInfo file in files)
{
string directoryname =  file.Directory>name;
string filename = file.Name;

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFolderPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\""; 
 
OleDbConnection cnn = new OleDbConnection(connectionString);
cnn.Opne();

DataTable dtsheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

foreach (DataRow drSheet in dtSheet.Rows)
{
  if (drSheet["TABLE_NAME"].ToString().Contains("xlnm"))
	sheetname = drSheet["TABLE_NAME"].ToString();
	
	OleDbCommand con = new OleDbCommand("select * from [" +sheetname+"]", cnn);
	OleDbDataAdapter adp = new OleDbDataAdapter(con);

	con.CommandTimeout = 0;
	
	using (OleDbDataReader reader =  con.ExecuteReader()
	{
		using (SqlBulkCopy dbc = new SqlBulkCopy(myadoconn)
		{
			dbc.Batchsize = 5000;
			dbc.DestinationTableName = "Table1";
			dbc.WriteToServer(reader);
		}
	}
}
SQL Server Integration Services
SQL Server Integration Services
A Microsoft platform for building enterprise-level data integration and data transformations solutions.
2,702 questions
Developer technologies | C#
0 comments No comments
{count} votes

Accepted answer
  1. Shivam Kumar 541 Reputation points
    2023-08-20T04:51:34.7966667+00:00

    Hi @Dinesh Kalva
    I guess changing the query from

    "select * from [" +sheetname+"]"
    

    to

    "select *,"+filename+","+sheetname+" from [" +sheetname+"]" 
    

    should work as filename is the variable you are storing the filename [string filename = file.Name;] and sheetname is the one which is holding the sheetname [sheetname = drSheet["TABLE_NAME"].ToString();]

    Assuming that your table has filename column before sheetname.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.