Introduction
In this blog, we are going to learn how to import Excel data into an SQL database table using C#. It also shows how bulk data is inserted into the table, checked for duplicate records, then updated. A stored procedure handles the user-defined table and its implementation. In short, this blog will help to understand bulk insertion of Excel data and the implementation of UDT (User Defined Table in SQL). Let's start now.
Step 1 - Create a database table in SQL
Below is the schema for the table:
- CREATE TABLE[dbo].[glsheetdata]
- (
- [glid] [INT] IDENTITY(1, 1) NOT NULL,
- [countryname] [NVARCHAR] (max) NULL,
- [company] [NVARCHAR] (max) NULL,
- [desc] [NVARCHAR] (max) NULL,
- [acctid] [NVARCHAR] (max) NULL,
- [accountdesc] [NVARCHAR] (max) NULL,
- [custid] [NVARCHAR] (max) NULL,
- [site] [NVARCHAR] (max) NULL,
- CONSTRAINT[PK_GLSheetData] PRIMARY KEY CLUSTERED ( [glid] ASC )WITH(
- pad_index = OFF, statistics_norecompute = OFF, ignore_dup_key = OFF,
- allow_row_locks = on, allow_page_locks = on) ON[PRIMARY]
- )
- ON[PRIMARY]
- textimage_on[PRIMARY]
- go
Step 2
Create upload Excel .cs class in project:
- public class UploadExcel {
- public static string DB_PATH = @ "";
- public static List < GLSheet > GLDataList = new List < GLSheet > ();
- private static Excel.Workbook MyBook = null;
- private static Excel.Application MyApp = null;
- private static Excel.Worksheet MySheet = null;
- private static int lastRow = 0;
- public static void InitializeExcel() {
- MyApp = new Excel.Application();
- MyApp.Visible = false;
- MyBook = MyApp.Workbooks.Open(DB_PATH);
- MySheet = (Excel.Worksheet) MyBook.Sheets[1]; // Explict cast is not required here
- lastRow = MySheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell).Row;
- }
- public static List < GLSheet > ReadMyExcel() {
- try {
- GLDataList.Clear();
- //First 4 rows are empty and not required. It varies to excel to excel accordingly
- for (int rowindex = 5; rowindex <= lastRow; rowindex++) {
- //System.Array MyValues = (System.Array)MySheet.get_Range("A" + index.ToString(), "D" + index.ToString()).Cells.Value;
- Microsoft.Office.Interop.Excel.Range CountryName = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 1];
- Microsoft.Office.Interop.Excel.Range COMPANY = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 2];
- Microsoft.Office.Interop.Excel.Range Desc = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 3];
- Microsoft.Office.Interop.Excel.Range AcctID = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 4];
- Microsoft.Office.Interop.Excel.Range AccountDesc = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 5];
- Microsoft.Office.Interop.Excel.Range CUSTID = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 6];
- Microsoft.Office.Interop.Excel.Range Site = (Microsoft.Office.Interop.Excel.Range) MySheet.Cells[rowindex, 7];
- GLDataList.Add(new GLSheet {
- CountryName = Convert.ToString(CountryName.Value),
- COMPANY = Convert.ToString(COMPANY.Value),
- Desc = Convert.ToString(Desc.Value),
- AcctID = Convert.ToString(AcctID.Value),
- AccountDesc = Convert.ToString(AccountDesc.Value),
- CUSTID = Convert.ToString(CUSTID.Value),
- Site = Convert.ToString(Site.Value),
- });
- //Insert data in slots of 100 rows
- UserBusiness userBis = new UserBusiness();
- if (rowindex % 100 == 0 || (lastRow - rowindex) < 100) {
- bool value = userBis.SaveGLSheetData(GLDataList);
- GLDataList = new List < Digiphoto.iMix.ClaimPortal.Model.GLSheet > ();
- }
- } //For loop completed
- } catch (Exception ex) {}
- return GLDataList;
- }
- public static void CloseExcel() {
- MyBook.Saved = true;
- MyApp.Quit();
- }
- }
Step 3
Now create the model which is used in the above code:
- public class GLSheet
- {
- public string CountryName { get; set; }
- public string COMPANY { get; set; }
- public string Desc { get; set; }
- public string AcctID { get; set; }
- public string AccountDesc { get; set; }
- public string CUSTID { get; set; }
- public string Site { get; set; }
- }
Now create a Business logic layer .cs class:
- public class UserBusiness : BaseBusiness
- {
- public bool SaveGLSheetData(List<GLSheet> glSheetData)
- {
- bool result = false;
- this.operation = () =>
- {
- UserAccess access = new UserAccess(this.Transaction);
- result = access.SaveGLSheetData(glSheetData);
- };
- this.Start(false);
- return result;
- }
- }
Step 5
Create a BaseBusiness .cs class:
- public class BaseBusiness
- {
- #region Declaration
- private bool _isTransactionRequired;
- public delegate void TransactionMethod();
- protected TransactionMethod operation;
- public BaseDataAccess m_Access;
- private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
- #endregion
- #region Public Methods
- public BaseDataAccess Transaction
- {
- get { return m_Access; }
- }
- public TransactionMethod Operation
- {
- set { operation = value; }
- }
- public BaseBusiness()
- {
- m_Access = new BaseDataAccess();
- }
- public BaseBusiness(BaseDataAccess transaction)
- {
- m_Access = transaction;
- }
- public virtual void ExecuteOperation(bool isTransactionRequired)
- {
- try
- {
- _isTransactionRequired = isTransactionRequired;
- if (isTransactionRequired)
- {
- this.BeginTransaction();
- this.operation();
- this.Commit();
- }
- else
- {
- this.OpenConnection();
- this.operation();
- // this.CloseConnection();
- }
- }
- catch(Exception ex)
- {
- RollBack();
- //CloseConnection();
- log.StartMethod();
- if (ex.InnerException != null)
- log.Error("ExecuteOperation: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
- else
- log.Error("ExecuteDataSet: " + ex.Message + ex.StackTrace.ToString());
- log.EndMethod();
- throw;
- }
- finally
- {
- CloseConnection();
- }
- }
- public bool Start(bool isTransactionRequired)
- {
- bool success = false;
- try
- {
- this.ExecuteOperation(isTransactionRequired);
- success = true;
- }
- catch(Exception ex)
- {
- log.StartMethod();
- if (ex.InnerException != null)
- log.Error("Start: " + ex.Message + ex.InnerException + ex.StackTrace.ToString());
- else
- log.Error("Start: " + ex.Message + ex.StackTrace.ToString());
- log.EndMethod();
- throw;
- }
- return (success);
- }
- #endregion
- #region Private Methods
- private void OpenConnection()
- {
- if (this.m_Access != null)
- this.m_Access.OpenConnection();
- }
- private void CloseConnection()
- {
- if (this.m_Access != null)
- this.m_Access.CloseConnection();
- }
- private void BeginTransaction()
- {
- if (this.m_Access != null)
- this.m_Access.BeginTransaction();
- }
- private void Commit()
- {
- if (this.m_Access != null)
- this.m_Access.CommitTransaction();
- }
- private void RollBack()
- {
- if (!_isTransactionRequired)
- return;
- if (this.m_Access != null)
- this.m_Access.RollbackTransaction();
- }
- #endregion
- }
Step 6
Create a Data Access layer .cs class:
- public class UserAccess : BaseDataAccess
- {
- #region Constrructor
- public UserAccess(BaseDataAccess baseaccess)
- : base(baseaccess)
- {
- }
- public UserAccess()
- {
- }
- #endregion
- /Save data to SQL database
- public bool SaveGLSheetData(List<GLSheet> glSheetData)
- {
- DBParameters.Clear();
- AddParameter("@ParamGLSheetDataUdt", DbHelper.ListToDataTable<GLSheet>(glSheetData));
- ExecuteNonQuery("usp_INSAndUPD_GLSheetData");
- return true;
- }
- }
Step 7
Create BaseDataAccess .cs file, which you can use in the application for many different methods

Join the conversation! Your thoughts help the community grow.