Quantcast
Channel: Welcome To TechBrothersIT
Viewing all 1876 articles
Browse latest View live

How to Change Recovery Model of Databases to Bulk_Logged in SQL Server - SQL Server Scripts

$
0
0

Scenario:

You are working as SQL Server DBA or developer, You need to write script that should change the database recovery model to Bulk-Logged for selected databases.

Below script can be used to change the recovery model for database or databases to Bulk-Logged. you can change the select query to include or exclude the database for which you want to change the recovery model to Bulk-Logged.

USE master 
go 
DECLARE @DBName VARCHAR(200) 
DECLARE db_cursor CURSOR FOR 
  --Make changes to Query to Include or Exclude database 
  SELECT NAME 
  FROM   sys.databases 
  WHERE  NAME NOT IN ( 'master', 'tempdb', 'model', 'msdb' ) 

OPEN db_cursor 

FETCH next FROM db_cursor INTO @DBName 

WHILE @@FETCH_STATUS = 0 
  BEGIN 
      IF ( (SELECT recovery_model_desc 
            FROM   sys.databases 
            WHERE  NAME = @DBName) <> 'Bulk_Logged' ) 
        BEGIN 
            DECLARE @SQL NVARCHAR(500) 

            SET @SQL='ALTER DATABASE [' + @DBName 
                     + '] SET RECOVERY Bulk_Logged' 

            PRINT @SQL 

            EXEC ( @SQL) 
        END 

      FETCH next FROM db_cursor INTO @DBName 
  END 

CLOSE db_cursor 

DEALLOCATE db_cursor 

--Check recovery model for all databases 
SELECT NAME AS DBName, 
       recovery_model_desc 
FROM   sys.databases 

C# - How to Convert CSV or Text files to Excel file in C#

$
0
0

Scenario: Download Script

You are working as C# developer, you need to write a program that should read text or csv files from source folder and convert them to an Excel file/s in destination folder. 

Each text or csv file will be converted to separate excel file. The sheet name will be text or file name. Each input file can have different columns as we are going to create separate excel for each text or csv file.


The below script can be used to convert multiple files from a folder to excel files. You can control the functionality with variable values. Let's say if you want to read only .csv files and convert them, Change the variable value =.csv.

Sample files
How to convert Text or CSV Files to Excel files in C#



Here is C# code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.IO;
using System.Data.OleDb;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{

//Declare Variables
// Provide source folder path where csv or text files exists
string SourceFolderPath = @"
C:\Source\";
//Provide the path where you like to have Excel files
string DestinationFolderPath = @"
C:\Destination\";
//Provide the extension of input text files such as .txt or .csv
string FileExtension = "
.txt";
// provide the file delimiter such as comma or pipe.
string FileDelimiter = "
,";
string CreateTableStatement = "
";
string ColumnList = "
";

//Reading file names one by one
string SourceDirectory = SourceFolderPath;
string[] fileEntries = Directory.GetFiles(SourceDirectory, "
*" + FileExtension);
foreach (string fileName in fileEntries)
{

//Read first line(Header) and prepare Create Statement for Excel Sheet
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
string filenameonly = (((fileName.Replace(SourceDirectory, "
")).Replace(FileExtension, "")).Replace("\\", ""));
CreateTableStatement = ("
Create Table [" + filenameonly + "] ([" + file.ReadLine().Replace(FileDelimiter, "] Text,[")) + "] Text)";
file.Close();

//Construct ConnectionString for Excel
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DestinationFolderPath + "\\" + filenameonly
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

//drop Excel file if exists
File.Delete(DestinationFolderPath + "\\" + filenameonly + ".xlsx");
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;

//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Cmd.CommandText = CreateTableStatement;
Excel_OLE_Cmd.ExecuteNonQuery();

//Writing Data of File to Excel Sheet in Excel File
int counter = 0;
string line;

System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "
[" + line.Replace(FileDelimiter, "],[") + "]";

}
else
{
string query = "
Insert into [" + filenameonly + "] (" + ColumnList
+ "
) VALUES('" + line.Replace(FileDelimiter, "','") + "')";
var command = query;
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();

}
counter++;
}
Excel_OLE_Con.Close();
SourceFile.Close();

}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I execute above program and it created excel files for all input text or csv files.
How to convert CSV or Text files to Excel Files in C#

 

C# - How to Import data from multiple CSV or Text files to an Excel sheet in C#

$
0
0

Scenario : Download Script

You are working as C# developer, you need to write a program that should read all the csv or text files from input folder and create a new Excel file with date-time and load the data to single sheet from all those input files.

As we are going to load the data from all the CSV or text files to single Excel Sheet. The input files should have same columns.

I am inserting the CSV file names into sheet as well so I would know that from which CSV data came, you can remove if you don't need that. I have put the comments for removing.

How to load multiple CSV Files to Excel Sheet in C#


The below code can be used to load all the CSV or Text files to Excel Sheet. By using different values for variable you can control the functionality of program. Let's say if you have the files with pipe delimiter, you can change the FileDelimiter variable ="|".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.IO;
using System.Data.OleDb;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{

//Declare Variables
//Provide the Source folder path where input files exist
string SourceFolderPath = @"
C:\Source\";
//Provide the destination folder path where you like to create Excel file
string DestinationFolderPath = @"
C:\Destination\";
// Provide the extension of input files such as .txt or .csv
string FileExtension = "
.txt";
// Provide the file delimiter such as comma or pipe
string FileDelimiter = "
,";
// Provide the name of Excel file you like to create
string ExcelFileName = "
TechBrothersITCourses";
string CreateTableStatement = "
";
string ColumnList = "
";
Int16 FileCnt = 0;

//Reading file names one by one
string SourceDirectory = SourceFolderPath;
string[] fileEntries = Directory.GetFiles(SourceDirectory, "
*" + FileExtension);
foreach (string fileName in fileEntries)
{


//Read first line(Header) and prepare Create Statement for Excel Sheet
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
string filenameonly = (((fileName.Replace(SourceDirectory, "
")).Replace(FileExtension, "")).Replace("\\", ""));
CreateTableStatement = ("
Create Table [" + ExcelFileName + "] ([" + file.ReadLine().Replace(FileDelimiter, "] Text,[")) + "] Text,[CSVFileName] Text)";
file.Close();

//Construct ConnectionString for Excel, also adding date-time
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DestinationFolderPath + "\\" + ExcelFileName + "_" + datetime
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;

//Create Sheet if does not exists
if (FileCnt == 0)
{
Excel_OLE_Cmd.CommandText = CreateTableStatement;
Excel_OLE_Cmd.ExecuteNonQuery();
}

//Writing Data of File to Excel Sheet in Excel File
int counter = 0;
string line;

System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
//I am also inserting CSV file name, if you don't like remove [CSVFileName]
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "],[CSVFileName]";

}
else
{
string query = "Insert into [" + ExcelFileName + "] (" +
ColumnList + ") VALUES('" +
line.Replace(FileDelimiter, "','")
//if you don't want to insert file name , then remove the filename+FileExtension part
+ "','" + filenameonly + FileExtension + "')";

var command = query;
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();

}
counter++;
}
Excel_OLE_Con.Close();
SourceFile.Close();
FileCnt += 1;

}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed above program and it created an Excel file with date-time and loaded all the input files from source folder to Excel sheet.

How to import or load multiple CSV files to an Excel File/ Excel Sheet in C#
 

C# - How to create Excel Sheet From CSV File and Keep appending data in Excel Sheet in C#

$
0
0

Scenario: Download Script

You are working as C# Developer, you need to create C# program that should read a CSV file from a folder and then create Excel File. The new file with same name will be dropped to folder every day. Next time when you run the program it should append the data to existing Excel. So we are covering two scenarios

  1. If Excel File does not exists, then create the Excel file and load the data
  2. If Excel file already exists then just load the data ( append the data to existing Excel sheet)
The below code can be used to achieve above requirement.
here is my sample file.
How to create and Load CVS Data to Excel file and if Excel exist, then append data  in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.IO;
using System.Data.OleDb;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{

//Declare Variables
// Source folder path
string SourceFolder = @"
C:\Source\";
// Provide Input file Name
string fileName = @"
TechbrothersIT-2015-01-02.txt";
//Provide the path where you like to have Excel files
string ExcelOutputfilePath = @"
C:\Destination\TechBrothersIT.xlsx";
// provide the file delimiter such as comma or pipe for input file.
string FileDelimiter = "
,";
string CreateTableStatement = "
";
string ColumnList = "
";

//Read first line(Header) and prepare Create Statement for Excel Sheet
//In case Excel file does not exists and we need to create
System.IO.StreamReader file = new System.IO.StreamReader(SourceFolder+fileName);
CreateTableStatement = ("
Create Table [" + fileName + "] (["
+ file.ReadLine().Replace(FileDelimiter, "
] Text,[")) + "] Text)";
file.Close();

//Construct ConnectionString for Excel
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + ExcelOutputfilePath
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

//If file exists , open it and load the data
if (File.Exists(ExcelOutputfilePath))
{
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;

}
//If file does not exists, create it and load the data
else
{
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;

//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Cmd.CommandText = CreateTableStatement;
Excel_OLE_Cmd.ExecuteNonQuery();
}

//Writing Data of File to Excel Sheet in Excel File
int counter = 0;
string line;

System.IO.StreamReader SourceFile =
new System.IO.StreamReader(SourceFolder+fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
//read header and build Column List for insert query
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";

}
else
{
//prepare inset query and execute to insert record in excel sheet
string query = "Insert into [" + fileName + "] (" + ColumnList
+ ") VALUES('" + line.Replace(FileDelimiter, "','") + "')";
var command = query;
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();

}
counter++;
}
Excel_OLE_Con.Close();
SourceFile.Close();


}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}

When I executed the program first time, the Excel file was not there. Excel file was created and 3 records from input files were loaded as shown below.
How to append data to Excel Sheet from CSV file in C#


I went back and remove 3 records and inserted the below records 
4,Windows 10,AppendTest

Executed the program again, and it appended the new records to existing Excel file as shown below.

How to Append records in Excel sheet by loading from CSV File in C#



C# - How to Import Multiple CSV files into Excel file to separate Excel Sheets in C#

$
0
0

Scenario: Download Script

You are working as C# developer, You need to write a program in C# that should read all CSV files from a folder and create a new Excel file with Date time and load CSV files to it. Each CSV file should be loaded to new excel sheet.


The below program can be used to load all the csv or text files to Excel file , each file to separate Excel sheet from a folder.

Here are couple of sample CSV files those I am using for testing the program.
How to Import multiple CSV files to Excel file dynamically in C#


C# Script to load multiple CSV files to Excel File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//Added below name spaces
using System.IO;
using System.Data.OleDb;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Declare Variables
//Provide the source folder path
string SourceFolderPath = @"
C:\Source\";
//Provide the Destination folder path
string DestinationFolderPath = @"
C:\Destination\";
//Provide the extension of input files such as .csv or .txt
string FileExtension = "
.csv";
//Provide the file delimiter such as comma or pipe
string FileDelimiter = "
,";
//Provide the Excel file name that you want to create
string ExcelFileName = "
TechBrothersIT";
string CreateTableStatement = "
";
string ColumnList = "
";

//Reading file names one by one
string SourceDirectory = SourceFolderPath;
string[] fileEntries = Directory.GetFiles(SourceDirectory, "
*" + FileExtension);
foreach (string fileName in fileEntries)
{


//Read first line(Header) and prepare Create Statement for Excel Sheet
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
string filenameonly = (((fileName.Replace(SourceDirectory, "
")).Replace(FileExtension, "")).Replace("\\", ""));
CreateTableStatement = ("
Create Table [" + filenameonly + "] (["
+ file.ReadLine().Replace(FileDelimiter, "
] Text,["))
+ "
] Text)";
file.Close();

//Construct ConnectionString for Excel
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DestinationFolderPath + "\\" + ExcelFileName + "_" + datetime
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";
OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;

//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Cmd.CommandText = CreateTableStatement;
Excel_OLE_Cmd.ExecuteNonQuery();

//Writing Data of File to Excel Sheet in Excel File
int counter = 0;
string line;

System.IO.StreamReader SourceFile =
new System.IO.StreamReader(fileName);
while ((line = SourceFile.ReadLine()) != null)
{
if (counter == 0)
{
ColumnList = "[" + line.Replace(FileDelimiter, "],[") + "]";

}
else
{
string query = "Insert into [" + filenameonly + "] ("
+ ColumnList + ") VALUES('"
+ line.Replace(FileDelimiter, "','")
+ "')";
var command = query;
Excel_OLE_Cmd.CommandText = command;
Excel_OLE_Cmd.ExecuteNonQuery();

}
counter++;
}
Excel_OLE_Con.Close();
SourceFile.Close();

}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed the above program with my sample csv files and it was able to create Excel file with multiple sheets and loaded the data from input files.

How to Import each CVS File to separate sheet in Excel file by using C#
 

C# - How to export database tables to Excel File dynamically in C#

$
0
0

Scenario : Download Script


You are working as Dot Net or C# Developer. You got this requirement where you have to Export all the Tables from a SQL Server Database to Excel File. Each Table should be export as SchemaName_TableName as Sheet to single Excel File.

So let's say you have 10 user tables in a Database and you would like to export all of them. The C# program should be able to create an Excel File with 10 sheets and load data from each table to separate excel sheet.

Below script can be used to export all the tables from a database to excel file. Provide the database name, Excel file name and path where it should be created in variables and you are all set.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Declare Variables
//Provide the excel file name you like to create
string ExcelFileName = "
TechBrothersIT";
//Provide the folder in which you would like to create Excel file
string FolderPath = @"
C:\Destination\";
string DatabaseName = "
TechBrothersIT";
ExcelFileName = ExcelFileName + "
_" + datetime;


OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

//Construct ConnectionString for Excel
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";

//drop Excel file if exists
File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx");

//Create Connection to SQL Server Database from which you like to export tables to Excel
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = (local); Initial Catalog ="+DatabaseName+"; " + "Integrated Security=true;";


//Read list of Tables with Schema from Database that you want to write to Excel file
string query = "
SELECT Schema_name(schema_id) AS SchemaName,name AS TableName FROM sys.tables WHERE is_ms_shipped = 0";


SqlCommand cmd = new SqlCommand(query, SQLConnection);
SQLConnection.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
SQLConnection.Close();

//Loop through datatable(dt) that has schema and table names
foreach (DataRow dt_row in dt.Rows)
{
string SchemaName = "
";
string TableName = "
";
object[] array = dt_row.ItemArray;
SchemaName = array[0].ToString();
TableName = array[1].ToString();

//Load Data into DataTable from SQL ServerTable
string queryString =
"
SELECT * from" + SchemaName + "." + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, SQLConnection);
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);

//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "
Create table [" + SchemaName
+ "
_" + TableName + "] ("
+ 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 [" + SchemaName + "_" + TableName + "] (" + 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();
}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed above program and it generated an Excel file with number of sheets equal to tables in my database and export data to those sheets from tables as shown below.
How to Export Multiple Tables from a database to Excel file in C#

C# - How to Export Stored Procedure Result Set to Excel file dynamically in C#

$
0
0

Scenario : Download Script

You are working as C# developer or Dot Net developer and you need to create a program that should execute Stored Procedure from SQL Server database and create an excel file for data returned by Stored Procedure. Let's assume that in in scenario, the Stored Procedure does not accept any parameters. 

The Stored Procedure definition can change any time that means that the number of columns returned by Stored Procedure can vary. Our program should be smart enough to create new Excel file without failing when definition of Stored Procedure change.

A new excel file should be generate with Date time on each execution. 

Let's create sample table and Stored Procedure first.

Createtable dbo.Customer(
Id INT,
Name VARCHAR(100),
Dob Date)

insertinto dbo.Customer values(1,'John','1980-01-02')
go

Createprocedure dbo.prc_Customer
AS
BEGIN
Select * From dbo.Customer
END

The below program can be used to run Stored Procedure in C# program and write results to Excel file dynamically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Declare Variables
//Provide Excel file name that you like to create
string ExcelFileName = "
Customer";
//Provide the source folder path where you want to create excel file
string FolderPath = @"
C:\Destination\";
//Provide the Stored Procedure Name
string StoredProcedureName = "
dbo.prc_Customer";
//Provide Excel Sheet Name
string SheetName = "
CustomerSheet";
//Provide the Database in which Stored Procedure exists
string DatabaseName = "
TechBrothersIT";
ExcelFileName = ExcelFileName + "
_" + datetime;

OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

//Construct ConnectionString for Excel
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";

//drop Excel file if exists
File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx");

//Create Connection to SQL Server Database from which you like to export tables to Excel
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = (local); Initial Catalog =" + DatabaseName + "; " + "Integrated Security=true;";


//Load Data into DataTable from by executing Stored Procedure
string queryString =
"
EXEC " + StoredProcedureName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, SQLConnection);
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);


//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "
Create table " + SheetName + " (" + 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 " + SheetName + "(" + 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();

}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}

I executed above program and it was able to export the results returned by Stored Procedure to Excel file as shown below.
How to Export Stored Procedure Results to Excel File in C#

C# - How to export Table or View Records to Excel file dynamically in C#

$
0
0

Scenario : Download Script

You are working as C# or Dot Net Developer, You got this requirement “Create a program that should read the data from SQL server Table, create an Excel file with Date time and load data from SQL server Table". On each execution the new Excel file should be created. Once problem with requirement is that the C# program should be able to handle new columns dynamically or if columns dropped from Table, it should not fail and simply start creating file with available columns.


The below C# code can be used to create console application that can get the records from a table or view and write to an excel file. Every time you will execute the program, a new excel file will be created with date-time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Declare Variables
//Provide the Excel file name you want to create
string ExcelFileName = "
Customer";
//Provide the folder in which Excel file should be created
string FolderPath = @"
C:\Destination\";
//Provide the table name or view name to Export records to Excel
string TableName = "
dbo.Customer";
//Provide the sheet name you like to create in excel file
string SheetName = "
Customer";
//Provide the Database Name in which table or view exists
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";
ExcelFileName = ExcelFileName + "
_" + datetime;

OleDbConnection Excel_OLE_Con = new OleDbConnection();
OleDbCommand Excel_OLE_Cmd = new OleDbCommand();

//Construct ConnectionString for Excel
string connstring = "
Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + FolderPath + ExcelFileName
+ "
;" + "Extended Properties=\"Excel 12.0 Xml;HDR=YES;\"";

//drop Excel file if exists
File.Delete(FolderPath + "\\" + ExcelFileName + ".xlsx");

//Create Connection to SQL Server Database from which you like to export tables to Excel
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "+SQLServerName+"; Initial Catalog =" + DatabaseName + "; " + "Integrated Security=true;";


//Load Data into DataTable from SQL ServerTable or view

string queryString =
"
SELECT * from" + TableName;
SqlDataAdapter adapter = new SqlDataAdapter(queryString, SQLConnection);
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);

//Use OLE DB Connection and Create Excel Sheet
Excel_OLE_Con.ConnectionString = connstring;
Excel_OLE_Con.Open();
Excel_OLE_Cmd.Connection = Excel_OLE_Con;
Excel_OLE_Cmd.CommandText = "
Create table " + SheetName + " (" + 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 " + SheetName + "(" + sqlCommandValue.TrimEnd(',') + ") 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();

}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed above program for dbo.Customer table and it created an excel file for me with 
date-time.
How to Export Table or View records to Excel file in C#




C# - How to Read Excel Sheet Data after Skipping Rows and Load to SQL Server Table in C#

$
0
0

Scenario : Download Script

You are working as C# developer or Dot Net Developer. You need to write a program that should be able to skip some rows from an Excel Sheet and load the remaining records to SQL Server Table. The program should be able to handle to load multiple Excel files.


Here is my sample excel sheet with some data.
How to Skip Rows in Excel Sheet and Export actual records to SQL Server Table in C#

As you can see that I have first 5 rows as company name. In your case you might have logo or any information. In my case, I need to start reading from A7 and load the data to dbo.Customer table.

We also validate the columns against our Table columns in database, let's say if there is a column in excel and it does not exists in database table, the program is going to ignore that column and insert the data for the columns which are present in excel and database table.

Let's create customer table first and then write C# code to skip the rows and load the data to table.

CREATETABLE [dbo].[Customer](
[Id] [int] NULL,
[Name] [varchar](100) NULL,
[Dob] [date] NULL
)


I created Console Application by using below C# code.
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the path where Excel files exists
string FolderPath = @"
C:\Source\";
//Provide the table name in which you want to load the data
string TableName = "
Customer";
//Provide the schema of table
string SchemaName = "
dbo";
//Provide the starting column for read actul records
string StartingColumn = "
A";
//Provide the end column till which you want to read
string EndingColumn = "
C";
//Provide the row number from which you like to start reading
string StartReadingFromRow = "
7";
//Provide the Database Name in which table or view exists
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";
var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Name, it can handle multiple sheets
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data so we can get the column header
OleDbCommand oconn = new OleDbCommand("select top 1 * from ["
+ sheetname + StartingColumn + StartReadingFromRow + ":" + EndingColumn + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();

//Prepare Header columns list so we can run against Database to get matching columns for a table.
//If columns does not exists in table, it will ignore and load only matching columns data
string ExcelHeaderColumn = "";
string SQLQueryToGetMatchingColumn = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'" + ",";
else
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'";
}

SQLQueryToGetMatchingColumn = "select STUFF((Select ',['+Column_Name+']' from Information_schema.Columns where Table_Name='" +
TableName + "' and Table_SChema='" + SchemaName + "'" +
"and Column_Name in (" + @ExcelHeaderColumn + ") for xml path('')),1,1,'') AS ColumnList";


//Create Connection to SQL Server Database from which you like to export tables to Excel
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "Data Source = "
+ SQLServerName + "; Initial Catalog ="
+ DatabaseName + "; "
+ "Integrated Security=true;";

//Get Matching Column List from SQL Server
string SQLColumnList = "";
SqlCommand cmd = SQLConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLConnection.Open();
SQLColumnList = (string)cmd.ExecuteScalar();
SQLConnection.Close();

//Use Actual Matching Columns to get data from Excel Sheet
OleDbConnection cnn1 = new OleDbConnection(ConStr);
cnn1.Open();
OleDbCommand oconn1 = new OleDbCommand("select " + SQLColumnList
+ " from [" + sheetname + StartingColumn
+ StartReadingFromRow + ":" + EndingColumn + "]", cnn1);
OleDbDataAdapter adp1 = new OleDbDataAdapter(oconn1);
DataTable dt1 = new DataTable();
adp1.Fill(dt1);
cnn1.Close();

SQLConnection.Open();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt1.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt1);
}
SQLConnection.Close();

}
}
}
}



catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}

I executed above program and it was able to skip the rows in excel sheet and loaded the actual data according as by variable values I have provided at start of program.

How to skip rows in Excel and import actual data rows to SQL Server table in C#

C# - Import Excel Files with Single or Multiple Sheets to SQL Server Tables according to Excel File Name Dynamically in C#

$
0
0

Scenario: Download Script

You are working as C# or Dot Net Developer, You receive single or multiple files in source folder daily. These Excel Files can have single or multiple Sheets. You need to load these Excel files to SQL Server Tables. The Excel File Name contains table name. Here are few sample files I created. I tried my best to create files names keeping in mind that you might get file names in different formats. 

Most common file formats are FileName_DateTime.xlsx or maybe you always get FileName_FileNumber etc.

How to Import Single or Multiple Excel files with single or multiple sheets to SQL Server Table according to Name in C#


Pay attention so file names. I am very much sure you will get your files from one of above format. I extracted the name from file. My table name is exactly like that. I have Customer and Product Tables.

The Excel files can have single or multiple sheets as long as the columns match with table columns, we are good to load them.

I opened couple of files and you can see it has multiple sheets.
Load Multiple Sheets from Single or Multiple Excel file to SQL Server Tables according to file name from a folder in C#

Let's create Product and Customer tables after talking a look into our Excel Sheets on each excel file.

CREATETABLE dbo.Customer (
id INT
,name VARCHAR(100)
,dob DATE
)
GO

CREATETABLE dbo.Product (
ProductId INT
,ProductName VARCHAR(100)
)

I have created the tables with dbo schema. You can change with different schema if you need to. 

The below C# code is used to create Console Application that should load all the files to SQL Server tables by using name part from file name.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the folder path where excel files are present
String FolderPath = @"
C:\Source\";
String TableName = "
";
//Provide the schema for tables in which we want to load Excel files
String SchemaName = "
dbo";
//Provide the Database Name in which table or view exists
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";


//Create Connection to SQL Server Database to import Excel file's data
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath
+ "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Remove All Numbers and other characters and leave alphabets for name
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex("[^a-zA-Z]");
TableName = rgx.Replace(file.Name, "").Replace("xlsx", "");

//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data so we can get the column header
OleDbCommand oconn = new OleDbCommand("select top 1 * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();

//Prepare Header columns list so we can run against Database to get matching columns for a table.
//If columns does not exists in table, it will ignore and load only matching columns data
string ExcelHeaderColumn = "";
string SQLQueryToGetMatchingColumn = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'" + ",";
else
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'";
}

SQLQueryToGetMatchingColumn = "select STUFF((Select ',['+Column_Name+']' from Information_schema.Columns where Table_Name='" +
TableName + "' and Table_SChema='" + SchemaName + "'" +
"and Column_Name in (" + @ExcelHeaderColumn + ") for xml path('')),1,1,'') AS ColumnList";


//Get Matching Column List from SQL Server
string SQLColumnList = "";
SqlCommand cmd = SQLConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLConnection.Open();
SQLColumnList = (string)cmd.ExecuteScalar();
SQLConnection.Close();

//Use Actual Matching Columns to get data from Excel Sheet
OleDbConnection cnn1 = new OleDbConnection(ConStr);
cnn1.Open();
OleDbCommand oconn1 = new OleDbCommand("select " + SQLColumnList
+ " from [" + sheetname + "]", cnn1);
OleDbDataAdapter adp1 = new OleDbDataAdapter(oconn1);
DataTable dt1 = new DataTable();
adp1.Fill(dt1);
cnn1.Close();


//Delete the row if all values are nulll
int columnCount = dt1.Columns.Count;
for (int i = dt1.Rows.Count - 1; i >= 0; i--)
{
bool allNull = true;
for (int j = 0; j < columnCount; j++)
{
if (dt1.Rows[i][j] != DBNull.Value)
{
allNull = false;
}
}
if (allNull)
{
dt1.Rows[i].Delete();
}
}
dt1.AcceptChanges();


SQLConnection.Open();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt1.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt1);
}
SQLConnection.Close();

}
}
}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I execute the Console Application and building it and it was able to load all the excel files with single or multiple sheets to different tables by using name part from file names.


How to load data from Excel File to SQL Server table according to the name of Excel file in C#

C# - Import Data To Tables according to Excel Sheet Names from Excel Files dynamically in C#

$
0
0

Scenario : Download Script

You are working as C# or Dot Net Developer, You get single or multiple Excel files in one of Source Folder. The Excel file can come with single or multiple sheets. Each sheet names will be matching with the tables you have in your Database. You need to write C# program that should loop through Excel files, then Excel Sheets and load the data to tables using Sheet Name as it is equal to Table Name.

The new sheets can be added or existing sheets can be dropped anytime. C# program should be dynamic to handle the number of sheets. As long as the sheet name matches with one of our table name, it should load the data. 

Here is my sample data. I have two Excel files, each contains two sheets, Product and Customer. Notice that the order of sheets does not matter. As long as the name matches with your Database tables we are good to load. 


How to Load multiple Sheets from Single or Multiple Excel Files to SQL Server Tables by using Sheet Name in C#


Let's create Product and Customer tables after talking a look into our Excel Sheets.

CREATETABLE dbo.Customer (
id INT
,name VARCHAR(100)
,dob DATE
)
GO

CREATETABLE dbo.Product (
ProductId INT
,ProductName VARCHAR(100)
)


I have created the Console application by using the below C# code to load sheets to tables.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the folder path where excel files are present
String FolderPath = @"
C:\Source\";
String TableName = "
";
//Provide the schema for tables in which we want to load Excel files
String SchemaName = "
dbo";
//Provide the Database Name in which table or view exists
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";


//Create Connection to SQL Server Database to import Excel file's data
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath
+ "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
TableName = sheetname.Replace("$", "");

//Load the DataTable with Sheet Data so we can get the column header
OleDbCommand oconn = new OleDbCommand("select top 1 * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();

//Prepare Header columns list so we can run against Database to get matching columns for a table.
//If columns does not exists in table, it will ignore and load only matching columns data
string ExcelHeaderColumn = "";
string SQLQueryToGetMatchingColumn = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'" + ",";
else
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'";
}

SQLQueryToGetMatchingColumn = "select STUFF((Select ',['+Column_Name+']' from Information_schema.Columns where Table_Name='" +
TableName + "' and Table_SChema='" + SchemaName + "'" +
"and Column_Name in (" + @ExcelHeaderColumn + ") for xml path('')),1,1,'') AS ColumnList";


//Get Matching Column List from SQL Server
string SQLColumnList = "";
SqlCommand cmd = SQLConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLConnection.Open();
SQLColumnList = (string)cmd.ExecuteScalar();
SQLConnection.Close();


//Use Actual Matching Columns to get data from Excel Sheet
OleDbConnection cnn1 = new OleDbConnection(ConStr);
cnn1.Open();
OleDbCommand oconn1 = new OleDbCommand("select " + SQLColumnList + " from [" + sheetname + "]", cnn1);
OleDbDataAdapter adp1 = new OleDbDataAdapter(oconn1);
DataTable dt1 = new DataTable();
adp1.Fill(dt1);
cnn1.Close();


//Delete the row if all values are nulll
int columnCount = dt1.Columns.Count;
for (int i = dt1.Rows.Count - 1; i >= 0; i--)
{
bool allNull = true;
for (int j = 0; j < columnCount; j++)
{
if (dt1.Rows[i][j] != DBNull.Value)
{
allNull = false;
}
}
if (allNull)
{
dt1.Rows[i].Delete();
}
}
dt1.AcceptChanges();


//Load Data from DataTable to SQL Server Table.
SQLConnection.Open();
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt1.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt1);
}
SQLConnection.Close();

}
}
}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


Build the program and then execute. I executed with my sample file and it loaded the Excel sheet data to tables as per names.

How to import data to tables from excel sheets according to the name of sheet in C#

 

C# - Import Excel Sheet Data with Excel File Name and Sheet Name in SQL Server Table in C#

$
0
0

Scenario : Download Script

You are working as C# or Dot Net Developer. You need to load Excel file/s with single or multiple sheets to SQL Server Table. As you will loading the records on daily basis, you would like to keep the information which records are loading from which Excel file and Sheet. You need to create C# Console Application that should be able to load data from Single/Multiple Excel files with single/Multiple Sheets and also log Excel file and Excel Sheet in table.

Here are my couple of Excel sample files with single and multiple Sheets.
How to Import single or multiple Excel Sheets from Single or Multiple Excel files to SQL Server Table with Excel File and Sheet Name in C#



I am going to create dbo.Customer Table to load these Excel Files data. As you can see the excel sheets, I have id, name and dob columns. The table dbo.Customer is going to have these columns and also FileName and SheetName so we can save Excel file name and Sheet Name from which data is loaded.

Createtable dbo.Customer(
id int,
name VARCHAR(100),
dob date,
FileName VARCHAR(100),
SheetName VARCHAR(100))


The below C# code can be used to create Console Application to load excel sheet's data to table with excel file name and sheet name.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;


namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the folder path where excel files are present
String FolderPath = @"
C:\Source\";
//Provide the table name in which you like to load data
String TableName = "
Customer";
//Provide the schema for tables in which we want to load Excel files
String SchemaName = "
dbo";
//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";


//Create Connection to SQL Server Database to import Excel file's data
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

string filename = "
";
filename = file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
//Loop through each sheet
foreach (DataRow drSheet in dtSheet.Rows)
{

if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data so we can get the column header
OleDbCommand oconn = new OleDbCommand("select top 1 * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();

//Prepare Header columns list so we can run against Database to get matching columns for a table.
//If columns does not exists in table, it will ignore and load only matching columns data
string ExcelHeaderColumn = "";
string SQLQueryToGetMatchingColumn = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'" + ",";
else
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'";
}

SQLQueryToGetMatchingColumn = "select STUFF((Select ',['+Column_Name+']' from Information_schema.Columns where Table_Name='" +
TableName + "' and Table_SChema='" + SchemaName + "'" +
"and Column_Name in (" + @ExcelHeaderColumn + ") for xml path('')),1,1,'') AS ColumnList";

//Get Matching Column List from SQL Server
string SQLColumnList = "";
SqlCommand cmd = SQLConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLConnection.Open();
SQLColumnList = (string)cmd.ExecuteScalar();
SQLConnection.Close();

//Use Actual Matching Columns to get data from Excel Sheet
OleDbConnection cnn1 = new OleDbConnection(ConStr);
cnn1.Open();
OleDbCommand oconn1 = new OleDbCommand("select " + SQLColumnList + ",'"
+ filename + "' AS FileName" + ",'" + sheetname
+ "' AS SheetName from [" + sheetname + "]", cnn1);
OleDbDataAdapter adp1 = new OleDbDataAdapter(oconn1);
DataTable dt1 = new DataTable();
adp1.Fill(dt1);
cnn1.Close();


//Delete the row if all values are nulll
int columnCount = dt1.Columns.Count;
for (int i = dt1.Rows.Count - 1; i >= 0; i--)
{
bool allNull = true;
for (int j = 0; j < columnCount; j++)
{
if (dt1.Rows[i][j] != DBNull.Value)
{
allNull = false;
}
}
if (allNull)
{
dt1.Rows[i].Delete();
}
}
dt1.AcceptChanges();


SQLConnection.Open();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt1.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt1);
}
SQLConnection.Close();

}
}

}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed the C# program and here is out output for my sample files. Data from Excel files with file name and sheet name is loaded successfully in Table as shown below.
How to Load data from Excel files to SQL Server table with excel file name and excel sheet name in C#

 

C#- How to convert each excel sheet to CSV file from Excel Files in C#

$
0
0

Scenario : Download Script

You are working as C# or Dot Net Developer. You got this requirement where you get single or multiple Excel files in Source or Input folder. Each File Can have single Sheet or Multiple Sheets. 
You need to create CSV file for each of the excel sheet in Destination Folder. The csv file name should be ExcelFileName_SheetName.csv.

Here are sample files with multiple Sheet that I am going to use for this post.

How to convert Excel Sheets to CVS File in C#


Customer_TechBrothersIT1.xlsx has two sheets in our case with columns Id, name and dob.
How to create CSV files from Excel Sheet in C#



Customer_TechBrothersIT2.xlsx has two sheets with columns id and name.
Create CSV file for each of the Excel Sheet from Excel Files in C#



I created Console Application in C# by using below code. The application will convert Excel Sheets to CSV files. The number of excel sheets can be less or more,program creates csv files dynamically.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the Source Folder path where excel files are present
string SourceFolderPath = @"
C:\Source\";
//Provide destination folder where you like to create CSV files from Excel Sheets
string DestinationFolderPath = @"
C:\Destination\";
//Provide the file delimiter such as comma or pipe
string FileDelimited = @"
,";

var directory = new DirectoryInfo(SourceFolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
string filename = "
";
fileFullPath = SourceFolderPath + "
\\" + file.Name;
filename = file.Name.Replace("
.xlsx", "");

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Names
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";

//Loop through each sheet
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
//cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);

//remove "$" from sheet name
sheetname = sheetname.Replace("$", "");

//Create CSV File and load data to it from Sheet
StreamWriter sw = new StreamWriter(DestinationFolderPath
+ "\\" + filename + "_" + sheetname + ".csv", false);
int ColumnCount = dt.Columns.Count;

// Write the Header Row to File
for (int i = 0; i < ColumnCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < ColumnCount - 1)
{
sw.Write(FileDelimited);
}
}
sw.Write(sw.NewLine);

// Write All Rows to the File
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < ColumnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < ColumnCount - 1)
{
sw.Write(FileDelimited);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}



Save the code and build. I executed the application with my sample excel files and it generate the CSV files for each of the sheet as shown below.






How to Convert Excel Sheets to CSV files for Single or Multiple Excel Files in C#



C# - How to create CSV file per Excel File and Load All Sheets from Excel File to it in C#

$
0
0

Scenario : Download Script

You are working as C# or Dot Net Developer. You got this requirement where you get single or multiple Excel files in Source or Input folder. Each File Can have single Sheet or Multiple Sheets.  If there are multiple Sheets they will have same metadata( Same Columns).
You need to create csv file per Excel file and load all sheets from it to newly created csv fil by using C#.

Here are sample files with multiple Sheet that I am going to use for this post. The Sheets on each Excel file has same number or columns.

How to create single CSV file per Excel File in C# 


Customer_TechBrothersIT1.xlsx has two sheets in our case with columns Id, name and dob.
Create CSV files dynamically from Excel Files and Sheets in C#


Customer_TechBrothersIT2.xlsx has two sheets with columns id and name.
How to Create Single CSV File per Excel Sheet and load data from all sheets in C#

I have used the below code to create Console Application. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the Source Folder path where excel files are present
string SourceFolderPath = @"
C:\Source\";
//Provide destination folder where you like to create CSV files from Excel Sheets
string DestinationFolderPath = @"
C:\Destination\";
//Provide the file delimiter such as comma or pipe
string FileDelimited = @"
,";


var directory = new DirectoryInfo(SourceFolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
string filename = "
";
fileFullPath = SourceFolderPath + "
\\" + file.Name;
filename = file.Name.Replace("
.xlsx", "");

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);


//Get Sheet Names
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
Int16 sheetcnt = 0;

//loop through each sheet
foreach (DataRow drSheet in dtSheet.Rows)
{
sheetcnt += 1;
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);

//remove "$" from sheet name
sheetname = sheetname.Replace("$", "");

//Create CSV File and load data to it from Sheet
StreamWriter sw = new StreamWriter(DestinationFolderPath + "\\" + filename + ".csv", true);
int ColumnCount = dt.Columns.Count;
//we are checking SheetCnt=1, so put header in csv for only one time for first sheet
if (sheetcnt == 1)
{
// Write the Header Row to File
for (int i = 0; i < ColumnCount; i++)
{
sw.Write(dt.Columns[i]);
if (i < ColumnCount - 1)
{
sw.Write(FileDelimited);
}
}
sw.Write(sw.NewLine);
}


// Write All Rows to the File
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < ColumnCount; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < ColumnCount - 1)
{
sw.Write(FileDelimited);
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
}
}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "
\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}



As I have two sample files with two sheets per file,If I will run the C# Console Application, It should create two csv files and load data from 4 sheets.

How to create csv file per Excel File and load data to it in C#



C# - How to Create Table per Excel File and Import all Sheet's Data Dynamically in C#

$
0
0

Scenario: Download Script

You are working as C# or dot Net Developer, you need to write a program that should create a Table if not exists per Excel File and load all sheet's data to it. As we are going to load all the sheets from single Excel file to a table, sheets should have same columns on each Excel file.

Here are our sample files.
How to create Table for each Excel file and load data from all sheets in C#

Customer_TechBrothersIT1.xlsx has two sheets in our case with columns Id, name and dob.
Create Table Dynamically for each Excel File in C# and Import All Sheets to Table


Customer_TechBrothersIT2.xlsx has two sheets with columns id and name.
How to load Multiple Sheets to SQL Server Table from a Excel File in C#

I have created Console Application by using below C# Code, it will create new table if does not exists for a excel file and load all the excel sheet's data to it.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the Source Folder path where excel files are present
String FolderPath = @"
C:\Source\";
//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";


//Create Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
string filename = "
";
fileFullPath = FolderPath + "
\\" + file.Name;
filename = file.Name.Replace("
.xlsx", "");

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath
+ "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
//Load DataTable with Sheet Data
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);


// Create Table if does not exists
string tableDDL = "";
tableDDL += "IF Not EXISTS (SELECT * FROM sys.objects WHERE object_id = ";
tableDDL += "OBJECT_ID(N'[dbo].[" + filename + "]') AND type in (N'U'))";
tableDDL += "Create table [" + filename + "]";
tableDDL += "(";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)" + ",";
else
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)";
}
tableDDL += ")";


SQLConnection.Open();
SqlCommand myCommand = new SqlCommand(tableDDL, SQLConnection);
myCommand.ExecuteNonQuery();

//Load the data from DataTable to SQL Server Table.
SqlBulkCopy blk = new SqlBulkCopy(SQLConnection);
blk.DestinationTableName = "[" + filename + "]";
blk.WriteToServer(dt);
}
SQLConnection.Close();
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}

}

I executed above C# code and it created tables from sample files as shown below and load the data from multiple sheet's to them.
Create SQL Table Dynamically from Excel file and load data in C#

Lets run query on created tables and take a look if data is loaded from Excel files correctly.
Table created form Customer_TechBrothersIT.xlsx Excel Sheet and Data Loaded from Sheets.


Data loaded to Table from Customer_TechBrothersIT2 Excel File in C# and data loaded successfully.


C# - How to create table for each of Excel Sheet Dynamically and Import Data in C#

$
0
0

Scenario: Download Script

You are working as C# or dot net Developer, you have tons of Excel files sitting in source folder. You got this requirement in which you need to write a program that should create table for each Excel sheet and load data.
The table name should be Excel File name_ Sheet name, I am going to use NVARCHAR(4000) as data type for all the fields, you can change as you like.

here are my excel files with multiple sheets.
Excel files with multiple sheets- How to create new table for each sheet and load data in C#

File Customer_TechBrothersIT1.xlsx has two sheets MySheet and Sheet1


Customer_TechBrothersIT2.xlsx has also two sheets. 4 Tables should be created for these two files and 2 sheets.


I created Console Application by using below C# code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the Source Folder path where excel files are present
String FolderPath = @"
C:\Source\";
//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";


//Create Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
string filename = "
";
fileFullPath = FolderPath + "
\\" + file.Name;
filename = file.Name.Replace("
.xlsx", "");

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileFullPath
+ "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=1\"";
OleDbConnection cnn = new OleDbConnection(ConStr);


//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);

//remove "$" from sheet name
sheetname = sheetname.Replace("$", "");

// Generate Create Table Script by using Header Column,
//It will drop the table if Exists and Recreate
string tableDDL = "";
tableDDL += "IF EXISTS (SELECT * FROM sys.objects WHERE object_id = ";
tableDDL += "OBJECT_ID(N'[dbo].[" + filename + "_" + sheetname + "]') AND type in (N'U'))";
tableDDL += "Drop Table [dbo].[" + filename + "_" + sheetname + "]";
tableDDL += "Create table [" + filename + "_" + sheetname + "]";
tableDDL += "(";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)" + ",";
else
tableDDL += "[" + dt.Columns[i].ColumnName + "] " + "NVarchar(max)";
}
tableDDL += ")";

SQLConnection.Open();
SqlCommand SQLCmd = new SqlCommand(tableDDL, SQLConnection);
SQLCmd.ExecuteNonQuery();

//Load the data from DataTable to SQL Server Table.
SqlBulkCopy blk = new SqlBulkCopy(SQLConnection);
blk.DestinationTableName = "[" + filename + "_" + sheetname + "]";
blk.WriteToServer(dt);
SQLConnection.Close();
}

}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed Console Application which I created by using above C# code and it created the table for each sheet from multiple Excel files and loaded the data.



New Table created for each Excel sheet and data loaded to it from Excel in C#

Let's take a look on data loaded to these Tables from Excel sheets

Table created for each Excel sheet and data import successfully in C# dynamically

2nd Sheet data loaded after creating new table by using C# code

C# - Import Multiple Excel Files with Multiple Sheets to Single SQL Server Table in C#

$
0
0

Scenario : Download Script

You are working as C# or dot net developer. You need to write a program that should be able to load single or multiple excel files with single or multiple excel sheets to single SQL Server table from a folder. All the sheets have the same columns.

The Excel file names and excel sheet names are not constant. They can change any time.

Here are couple of sample files those I created for test the below program.
How to import data from multiple excel files with single or multiple excel sheets to SQL Server Table in C#

Let's create SQL Server Table first before we use it in our C# program.

CREATETABLE [dbo].[tblCustomer](
[id] intNULL,
[name] varchar(100) NULL,
[dob] dateNULL
)
I used below C# code to create Console Application.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the Source Folder path where excel files are present
String FolderPath = @"
C:\Source\";
//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";
//Provide the table name in which you want to load excel sheet's data
String TableName = @"
tblCustomer";
//Provide the schema of table
String SchemaName = @"
dbo";


//Create Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";


//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Name
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";

//Loop through each sheet
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Get data from Excel Sheet to DataTable
OleDbConnection Conn = new OleDbConnection(ConStr);
Conn.Open();
OleDbCommand oconn = new OleDbCommand("select * from [" + sheetname + "]", Conn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
Conn.Close();

SQLConnection.Open();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt);
}
SQLConnection.Close();

}
}
}
}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}
I executed above C# Console Application and it loaded data from multiple excel files with multiple sheets to SQL Server Table.
How to import multiple excel files with multiple Sheets to SQL Server Table in C#




C# - How to Import Excel Sheet to SQL Server Table in C#

$
0
0

Scenario: Download Script

You are working as C# or dot net developer in insurance company. You need to write a C# code that should read the data from Excel Sheet and load to SQL Server Table.

How to Import Excel Sheet Data to SQL Server Table in C#

Let's create the table in database first after studying our data for Customer Sheet.

CREATETABLE [dbo].[tblCustomer](
[id] intNULL,
[name] varchar(100) NULL,
[dob] dateNULL
)


I created Console Application by using below C# code that will be able to import data from Customer Excel sheet to our dbo.tblCustomer table. 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{

//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";
//Provide the table name in which you want to load excel sheet's data
String TableName = @"
tblCustomer";
//Provide the schema of table
String SchemaName = @"
dbo";
//Provide Excel file path
string fileFullPath = @"
C:\Source\Customer_1.xlsx";
//Provide Sheet Name you like to read
string SheetName = "
Customer";


//Create Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";


//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);


//Get data from Excel Sheet to DataTable
OleDbConnection Conn = new OleDbConnection(ConStr);
Conn.Open();
OleDbCommand oconn = new OleDbCommand("select * from [" + SheetName + "$]", Conn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
Conn.Close();

SQLConnection.Open();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt);
}
SQLConnection.Close();

}
catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}


I executed Console application and it was able to read the data from Customer sheet from Excel file and imported into SQL server Table.
How to import data from Excel Sheet to SQL Server table in C#
 

C# - How to get Excel file's information and import to SQL Server Table in C#

$
0
0

Scenario : Download Script

You are working as C# or Dot Net developer, You are asked to create a program that should collection the information for all the excel files in a folder such as

  • Folder Path
  • Excel File Name
  • Sheet Name/s from Each Excel file
  • Number of Records per Sheet
  • Last Date Modified
  • Last Access Date
  • File Size in KB
and insert into SQL Server table.
The information can be used for multiple purposes such as
  • Estimate the storage and do capacity planning
  • To find data in some file, you will be able to get Sheet Names so you don't have to open it
  • Data Growth can be estimated as you are going to log Row Count from each sheet
  • You can tell what time file was accessed  and if somebody made any change to file.
Let's create Table in SQL Server Database by using below DDL Statement so we can store Excel file information.


Createtable dbo.ExcelFileInformation(
id intidentity(1,1),
FolderPath VARCHAR(255),
FileName VARCHAR(255),
SheetName VARCHAR(255),
RowsInt,
LastDateModified DateTime,
LastAccessTime Datetime,
FileSizeinKB Int)

I used below C# code to create Console Application that can be used to get excel file's information and insert into dbo.ExcelFileInformation.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the source folder path where excel files are present
string FolderPath = @"
C:\Source\";
//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";
//Provide the table name in which you want to load excel file's information
String TableName = @"
ExcelFileInformation";
//Provide the schema of table
String SchemaName = @"
dbo";

//Create Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Names
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";

//Get Row Count for each sheet
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();
OleDbCommand oconn = new OleDbCommand("select count(*) AS RowCnt from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
string RC = "";
foreach (DataRow row in dt.Rows)
{
object[] array = row.ItemArray;
RC = array[0].ToString();
}

cnn.Close();
//If sheets start with Numbers, when we read it add extra '(single quote), this will take //care of that part
sheetname = sheetname.Replace("'", "");


//Prepare Insert Query with file info to insert into table
string InsertQuery = "";
InsertQuery = " Insert into [" + SchemaName + "].[" + TableName + "] (";
InsertQuery += "[FolderPath],[FileName],[SheetName],[Rows],[LastDateModified],[LastAccessTime],[FileSizeinKB])";
InsertQuery += "Values('" + FolderPath + "','" + file.Name + "','" +
sheetname + "','" + RC + "','" + file.LastWriteTime
+ "','" + file.LastAccessTime + "',"
+ file.Length / 1024 + ")";

//Run Insert Query to Insert Data into SQL Server Table
SqlCommand cmd = SQLConnection.CreateCommand();
cmd.CommandText = InsertQuery;
SQLConnection.Open();
cmd.ExecuteNonQuery();
SQLConnection.Close();
}
}
}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}

I executed Console application with above C# code.It was able to read multiple excel files with multiple sheets and inserted the information into sql server table.
How to read excel file's information in C# and load to SQL Server Table 


C# - Import Only Matching Column's Data to SQL Server Table from Excel Files Dynamically in C#

$
0
0

Scenario: Download Script

You are working as C# or Dot Net Developer.  You get Excel files in source folder with single or multiple sheets that you need to load into SQL Server Table called dbo.Customer in TechbrothersIT Database.
Here is the definition of dbo.Customer Table.

CREATETABLE dbo.Customer (
id INT
,NAME VARCHAR(50)
,dob DATE
)

There are some problems with Excel Sheet data
1) Sometime you get exact number of columns in Sheet
2) Sometime you get extra columns in Excel file Sheets
3) Sometime you get less columns than your table definition.
4) Excel File can be provided with any name in given folder
5) Sheet Name can change as well in each Excel file

You need to write C# program that should be able to handle above situation and load all data for columns which match with our SQL Server Table Definition( dbo.Customer). 

It should ignore extra columns in Excel sheets and load the matching columns data without error. If we receive less columns in Excel sheet, It should go ahead and load that into table. 

This is how our excel files and sheets looks like
How to load data from Excel to SQL server Table for Matching Columns only in C#

Sheet Data for Customer_TechBrothersIT1.xlsx

Load Data from Excel Sheet Dynamically in SQL Server Table  by using C#


Sheet Data for Customer_TechBrothersIT2.xlsx
Import data from Excel files dynamically to SQL Server for matching columns dynamically in C#


Sheet Data for Customer_TechBrothersIT3.xlsx
Less Columns provided as compared to table in Excel Sheet , need to loaded to SQL table by using C#


The below C# code can be used to import data from multiple excel files with single or multiple excel sheets for matching columns.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
//added below name spaces
using System.IO;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;

namespace TechBrothersIT.com_CSharp_Tutorial
{
class Program
{
staticvoid Main(string[] args)
{
//the datetime and Log folder will be used for error log file in case error occured
string datetime = DateTime.Now.ToString("yyyyMMddHHmmss");
string LogFolder = @"C:\Log\";
try
{
//Provide the source folder path where excel files are present
string FolderPath = @"
C:\Source\";
//Provide the Database Name
string DatabaseName = "
TechbrothersIT";
//Provide the SQL Server Name
string SQLServerName = "
(local)";
//Provide the table name
String TableName = @"
Customer";
//Provide the schema of table
String SchemaName = @"
dbo";

//Create Connection to SQL Server Database
SqlConnection SQLConnection = new SqlConnection();
SQLConnection.ConnectionString = "
Data Source = "
+ SQLServerName + "
; Initial Catalog ="
+ DatabaseName + "
; "
+ "
Integrated Security=true;";

var directory = new DirectoryInfo(FolderPath);
FileInfo[] files = directory.GetFiles();

//Declare and initilize variables
string fileFullPath = "
";

//Get one Book(Excel file at a time)
foreach (FileInfo file in files)
{
fileFullPath = FolderPath + "
\\" + file.Name;

//Create Excel Connection
string ConStr;
string HDR;
HDR = "
YES";
ConStr = "
Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
+ fileFullPath + "
;Extended Properties=\"Excel 12.0;HDR=" + HDR + ";IMEX=0\"";
OleDbConnection cnn = new OleDbConnection(ConStr);

//Get Sheet Names
cnn.Open();
DataTable dtSheet = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
string sheetname;
sheetname = "";
foreach (DataRow drSheet in dtSheet.Rows)
{
if (drSheet["TABLE_NAME"].ToString().Contains("$"))
{
sheetname = drSheet["TABLE_NAME"].ToString();

//Load the DataTable with Sheet Data so we can get the column header
OleDbCommand oconn = new OleDbCommand("select top 1 * from [" + sheetname + "]", cnn);
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
cnn.Close();

//Prepare Header columns list so we can run against Database to get matching columns for a table.
string ExcelHeaderColumn = "";
string SQLQueryToGetMatchingColumn = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
if (i != dt.Columns.Count - 1)
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'" + ",";
else
ExcelHeaderColumn += "'" + dt.Columns[i].ColumnName + "'";
}

SQLQueryToGetMatchingColumn = "select STUFF((Select ',['+Column_Name+']' from Information_schema.Columns where Table_Name='" +
TableName + "' and Table_SChema='" + SchemaName + "'" +
"and Column_Name in (" + @ExcelHeaderColumn
+ ") for xml path('')),1,1,'') AS ColumnList";


//Get Matching Column List from SQL Server
string SQLColumnList = "";
SqlCommand cmd = SQLConnection.CreateCommand();
cmd.CommandText = SQLQueryToGetMatchingColumn;
SQLConnection.Open();
SQLColumnList = (string)cmd.ExecuteScalar();
SQLConnection.Close();

//Use Actual Matching Columns to get data from Excel Sheet
OleDbConnection cnn1 = new OleDbConnection(ConStr);
cnn1.Open();
OleDbCommand oconn1 = new OleDbCommand("select " + SQLColumnList
+ " from [" + sheetname + "]", cnn1);
OleDbDataAdapter adp1 = new OleDbDataAdapter(oconn1);
DataTable dt1 = new DataTable();
adp1.Fill(dt1);
cnn1.Close();

SQLConnection.Open();
//Load Data from DataTable to SQL Server Table.
using (SqlBulkCopy BC = new SqlBulkCopy(SQLConnection))
{
BC.DestinationTableName = SchemaName + "." + TableName;
foreach (var column in dt1.Columns)
BC.ColumnMappings.Add(column.ToString(), column.ToString());
BC.WriteToServer(dt1);
}
SQLConnection.Close();
}
}

}
}

catch (Exception exception)
{
// Create Log File for Errors
using (StreamWriter sw = File.CreateText(LogFolder
+ "\\" + "ErrorLog_" + datetime + ".log"))
{
sw.WriteLine(exception.ToString());

}

}

}
}
}

I executed the C# Console application that I created by using above C# code. It loaded the data from sample Excel files from multiple excel sheets for matching columns. Also I noticed that BulkCopy is case sensitive when it comes to match the columns. Make sure you always have the Column Name in same case as you have in SQL Server Table.

How to import data from multiple excel files to sql server table for matching columns only in C#



Viewing all 1876 articles
Browse latest View live