I am trying to copy data from Excel spreadsheet to SQL database. My database table looks like this:
EmployeeID int
EmployeeNumber varchar(50)
EmployeeName varchar(500)
EmployeeId is an identity column set to autoincrement by 1. This is how I am copying the data.
When i run the code, EmployeeName gets inserted in EmployeeNumber field and EmployeeName field is NULL.
If I remove the Identity column then EmployeeNumber gets copied in employeeNumber field and EmployeeName gets copied to EmployeeName field.
I need to keep the identity column.
How can I copy the data from excel to sql and have the identity column too.
This is what I have in the code in the console application:
using ClosedXML.Excel;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;
using System.Configuration;
namespace LatestEmployeeData;
public class Program
{
static void Main(string[] args)
{
string filename = ConfigurationManager.AppSettings["EmployeeExcel"];
string connectionString = ConfigurationManager.AppSettings["DbConnection"];
using (var con = new SqlConnection(connectionString))
{
con.Open();
using (var ds = ExcelToDataSet(filename, true))
{
foreach (DataTable dt in ds.Tables)
{
using (var bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName ="Employee";
bulkCopy.WriteToServer(dt);
}
}
}
}
}
static DataSet ExcelToDataSet(string excelFileName, bool useHeader)
{
var ds = new DataSet();
using (var workbook = new XLWorkbook(excelFileName))
{
foreach (var worksheet in workbook.Worksheets)
{
var first = true;
var dt = ds.Tables.Add(worksheet.Name);
dt.BeginInit();
//dt.Columns.Add("EmployeeId", typeof(int));
dt.Columns.Add("EmployeeNumber", typeof(string));
dt.Columns.Add("EmployeeName", typeof(string));
dt.EndInit();
dt.BeginLoadData();
foreach (var row in worksheet.Rows())
{
if (useHeader && first)
{
first = false;
}
else
{
object[] values = {
row.Cell(1).Value,
row.Cell(2).Value,
};
dt.Rows.Add(values);
}
}
dt.EndLoadData();
dt.AcceptChanges();
}
}
return ds;
}
}
My Excel spreadsheet has these columns
EmployeeNum
EmployeeName
DepartmentID and many other columns
I just want to copy EmployeeNumber and EmployeeName from Excel spreadsheet to SQL table.