Share via

need help on methods

Dinesh Kalva 100 Reputation points
2023-08-06T18:33:17.78+00:00

Hi, I am working on script task in SSIS. I have to read excel files having headers with 100 columns with huge data. I want to insert column headers into Table1 and data into Table2. Could you please help me what code should go into CreateHeadersTable and CreateDataTable methods? btw, this is chatgpt generated code.

using System;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
namespace ExcelImportExample
{
	class Program
	{
		static void Main(string[] args)
		{
			string excelFolderPath = @"C:\YourFolderPath\"; 
				// Update with your folder path             
			string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFolderPath + ";Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
			string sqlServerConnectionString = "Server=YourServer;Database=YourDatabase;User Id=YourUsername;Password=YourPassword;";
			using(OleDbConnection excelConnection = new OleDbConnection(connectionString)) using(SqlConnection sqlConnection = new SqlConnection(sqlServerConnectionString))
			{
				excelConnection.Open();
				sqlConnection.Open();
				foreach(string excelFile in System.IO.Directory.GetFiles(excelFolderPath, "*.xlsx"))
				{
					using(OleDbCommand excelCommand = new OleDbCommand("SELECT * FROM [Sheet1$]", excelConnection))
					using(OleDbDataReader excelReader = excelCommand.ExecuteReader())
					{
						DataTable schemaTable = excelReader.GetSchemaTable()
						CreateHeadersTable(sqlConnection, schemaTable);
						// Create data table                         
						DataTable dataTable = CreateDataTable(sqlConnection, schemaTable);
						using(SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(sqlConnection))
						{
							sqlBulkCopy.DestinationTableName = "YourDataTableName";
							sqlBulkCopy.WriteToServer(dataTable);
						}
					}
				}
			}
		}
		static void CreateHeadersTable(SqlConnection connection, DataTable schemaTable)
		{ // Create headers table dynamically using schemaTable             
			// Insert header names into the table             
			// Execute SQL commands         
		}
		static DataTable CreateDataTable(SqlConnection connection, DataTable schemaTable)
		{ // Create data table dynamically using schemaTable
			// Return the created DataTable        
		}
	}
}
SQL Server Integration Services
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Your answer

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