Reading Merged Cell From Excel Using Microsoft.Office.Interop.Excel in C#

Introduction

It's very simple and easy for us to read and upload an Excel file with normal columns and you'll find ample articles for that. But when you want to read an Excel file with merged cells then the way to do that is a little different. Using OLEDB anyone can read the Excel file that has a header at the first row and the rest of the data is vertically grown with no merged columns (in other words a single-celled single value). But if you try to read an Excel file that contains a merged cell using OLEDB then the result will be that it is in an unexpected format. The workaround is to either use a third-party DLL or you can use one that Microsoft provides, Microsoft.office.Interop.Excel.dll.

This was the requirement for me when working on a project. We needed to import data from an Excel file having merged cells and place the data inside SQL without duplication and also properly format the relationship among multiple tables, because the tables were highly normalized.

Let's first create a sample Excel file. The following is the snapshot of it.

Excel file

As you can see, I have multiple fruit names along with their benefits. For each fruit there are multiple benefits. Now let's say you have tables in your SQL that store the name of the fruit, another table that stores the benefits offered and a third table that has the mapping of the fruit with that of the benefits. In that case you need to read the Excel file in accordance with your SQL table and also form the relationship with that of the benefits while reading. Also a special attention while reading must be taken about the duplication of the data, in other words no fruit or benefits should be duplicated and also their mapping.

The following is the SQL table's script:

  1. create table Fruits    
  2. (    
  3. FruitId int identity(1,1)not null,    
  4. FruitName varchar(30),    
  5. Constraint pkFruitId primary key(FruitId))    
  6.     
  7. create table Benefits    
  8. (    
  9. BenefitID int identity(1,1) not null,    
  10. BenefitName varchar(200)not null,    
  11. constraint pkBenefitId primary key(BenefitID)    
  12. )    
  13.     
  14. create table FruitBenefit    
  15. (    
  16. FruitBenefitID int identity(1,1)not null,    
  17. FruitId int not null,    
  18. BenefitId int not null,    
  19. constraint fkFruitId foreign key(FruitID)references Fruits(FruitID),    
  20. constraint fkbenefitId foreign key(BenefitId)references Benefits(BenefitId)    
  21. )    
Okay everything is now in place. The dilemma now is, how to read the Excel merged cell. Well to read an Excel merged cell its simple, whatever columns are merged all form a range and we can get the data from that range. In simple terms we can say that only the first cell of the merged cell contains the data and the rest of them contain an empty string. Merging a cell doesn't mean that the cell does not exist, it exists but doesn't have a value.

NOTE: For reading an Excel file we are using Microsoft.Office.Interop.Excel.dll.

You need to add a reference for Microsoft.Office.Interop.Excel.dll to your application. Here I'm using a Console Application for demonstration purposes.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Microsoft.Office.Interop.Excel;  
  6. using System.Data.SqlClient;  
  7. using System.Data;  
  8.   
  9. namespace ExcelWithMergedCells  
  10. {  
  11.     internal sealed class Program  
  12.     {  
  13.         SqlConnection con;  
  14.         SqlDataAdapter da;  
  15.         System.Data.DataTable dtFruits, dtBenefits, dtFruitBenefits;  
  16.         DataSet dsTemp;  
  17.         SqlCommand cmd;  
  18.         const string DBCon = "Server=VISHALG;Initial Catalog=Practice;Integrated Security=true";  
  19.         const string EXCEL_PATH = @"D:\Vishal\Mvc\Practice\ExcelWithMergedCells\DummyData.xlsx";  
  20.         Application excelApplication = null;  
  21.         Workbook excelWorkBook = null;  
  22.   
  23.         private DataColumn CreateIdentityColumn(string columnName = "SrNo")  
  24.         {  
  25.             DataColumn dc = new DataColumn(columnName);  
  26.             dc.AutoIncrement = true;  
  27.             dc.AutoIncrementSeed = dc.AutoIncrementStep = 1;  
  28.             return dc;  
  29.         }  
  30.   
  31.         private void ReadExcelFile()  
  32.         {  
  33.             try  
  34.             {  
  35.                 dsTemp = new DataSet();  
  36.                 if (dsTemp.Tables.Count == 0)  
  37.                 {  
  38.                     dtFruits = dsTemp.Tables.Add(TableNames.Fruits.ToString());  
  39.                     dtFruits.Columns.Add(CreateIdentityColumn("FruitId"));  
  40.                     dtFruits.Columns.Add("FruitName");  
  41.   
  42.                     dtBenefits = dsTemp.Tables.Add(TableNames.Benefits.ToString());  
  43.                     dtBenefits.Columns.Add(CreateIdentityColumn("BenefitID"));  
  44.                     dtBenefits.Columns.Add("BenefitName");  
  45.   
  46.                     dtFruitBenefits = dsTemp.Tables.Add(TableNames.FruitBenefit.ToString());  
  47.                     dtFruitBenefits.Columns.Add(CreateIdentityColumn("FruitBenefitID"));  
  48.                     dtFruitBenefits.Columns.Add("FruitId");  
  49.                     dtFruitBenefits.Columns.Add("BenefitId");  
  50.                 }  
  51.   
  52.                 excelApplication = new Application();  
  53.                 //Opening/Loading the workBook in memory  
  54.                 excelWorkBook = excelApplication.Workbooks.Open(EXCEL_PATH);  
  55.   
  56.                 //retrieving the worksheet counts inside the excel workbook  
  57.                 int workSheetCounts = excelWorkBook.Worksheets.Count;  
  58.                 int totalColumns = 0;  
  59.                 Range objRange = null;  
  60.   
  61.                 for (int sheetCounter = 1; sheetCounter <= workSheetCounts; sheetCounter++)  
  62.                 {  
  63.                     Worksheet workSheet = excelWorkBook.Sheets[sheetCounter];  
  64.   
  65.                     totalColumns = workSheet.UsedRange.Cells.Columns.Count + 1;  
  66.   
  67.                     object[] data = null;  
  68.   
  69.                     //Iterating from row 2 because first row contains HeaderNames  
  70.                     for (int row = 2; row < workSheet.UsedRange.Cells.Rows.Count; row++)  
  71.                     {  
  72.                         data = new object[totalColumns - 1];  
  73.   
  74.                         for (int col = 1; col < totalColumns; col++)  
  75.                         {  
  76.                             objRange = workSheet.Cells[row, col];  
  77.                             if (objRange.MergeCells)  
  78.                             {  
  79.                                 data[col - 1] = Convert.ToString(((Range)objRange.MergeArea[1, 1]).Text).Trim();  
  80.                             }  
  81.                             else  
  82.                             {  
  83.                                 data[col - 1] = Convert.ToString(objRange.Text).Trim();  
  84.                             }  
  85.                         }  
  86.                         AddRow(data);  
  87.                     }  
  88.                 }  
  89.             }  
  90.             catch (Exception ex)  
  91.             {  
  92.                 Console.WriteLine(ex.Message);  
  93.             }  
  94.             finally  
  95.             {  
  96.                 //Release the Excel objects     
  97.                 excelWorkBook.Close(false, System.Reflection.Missing.Value, System.Reflection.Missing.Value);  
  98.                 excelApplication.Workbooks.Close();  
  99.                 excelApplication.Quit();  
  100.                 excelApplication = null;  
  101.                 excelWorkBook = null;  
  102.   
  103.                 GC.GetTotalMemory(false);  
  104.                 GC.Collect();  
  105.                 GC.WaitForPendingFinalizers();  
  106.                 GC.Collect();  
  107.                 GC.GetTotalMemory(true);  
  108.                   
  109.                 DumbDataIntoSql();  
  110.             }  
  111.         }  
  112.   
  113.         private void AddRow(object[] data)  
  114.         {  
  115.             int check = 0;  
  116.             for (int tableCounter = 0; tableCounter < dsTemp.Tables.Count; tableCounter++)  
  117.             {  
  118.                 TableNames tableName = (TableNames)Enum.Parse(typeof(TableNames), dsTemp.Tables[tableCounter].TableName);  
  119.                 switch (tableName)  
  120.                 {  
  121.                     case TableNames.Fruits:  
  122.   
  123.                         check = dtFruits.AsEnumerable().Where(x => x["FruitName"].ToString().Equals(data[0].ToString(), StringComparison.InvariantCultureIgnoreCase)).Count();  
  124.   
  125.                         if (check == 0 && !string.IsNullOrEmpty(Convert.ToString(data[0])))  
  126.                         {  
  127.                             DataRow dr = dtFruits.NewRow();  
  128.                             dr["FruitName"] = data[0].ToString();  
  129.                             dtFruits.Rows.Add(dr);  
  130.                         }  
  131.                         break;  
  132.                     case TableNames.Benefits:  
  133.   
  134.                         check = dtBenefits.AsEnumerable().Where(x => x["BenefitName"].ToString().Equals(data[1].ToString(), StringComparison.InvariantCultureIgnoreCase)).Count();  
  135.   
  136.                         if (check == 0 && !string.IsNullOrEmpty(Convert.ToString(data[1])))  
  137.                         {  
  138.                             DataRow dr = dtBenefits.NewRow();  
  139.                             dr["BenefitName"] = data[1].ToString();  
  140.                             dtBenefits.Rows.Add(dr);  
  141.                         }  
  142.                         break;  
  143.                     case TableNames.FruitBenefit:  
  144.   
  145.                         int fruitID = dtFruits.AsEnumerable().Where(x => x["FruitName"].ToString().Equals(data[0].ToString(), StringComparison.InvariantCultureIgnoreCase)).Select(x => Convert.ToInt32(x["FruitID"].ToString())).FirstOrDefault();  
  146.   
  147.                         int benefitID = dtBenefits.AsEnumerable().Where(x => x["BenefitName"].ToString().Equals(data[1].ToString(), StringComparison.InvariantCultureIgnoreCase)).Select(x => Convert.ToInt32(x["BenefitID"].ToString())).FirstOrDefault();  
  148.   
  149.                         check = dtFruitBenefits.AsEnumerable().Where(x => Convert.ToInt32(x["FruitId"].ToString()) == fruitID && Convert.ToInt32(x["BenefitID"].ToString()) == benefitID).Count();  
  150.   
  151.                         if (check == 0 && fruitID != 0 && benefitID != 0)  
  152.                         {  
  153.                             DataRow dr = dtFruitBenefits.NewRow();  
  154.                             dr["FruitID"] = fruitID;  
  155.                             dr["BenefitID"] = benefitID;  
  156.                             dtFruitBenefits.Rows.Add(dr);  
  157.                         }  
  158.                         break;  
  159.                 }  
  160.             }  
  161.         }  
  162.   
  163.         private void DumbDataIntoSql()  
  164.         {  
  165.             try  
  166.             {  
  167.                 int rowsAffected = 0;  
  168.                 Console.WriteLine("Dumping Data into SQL Tables\n\n");  
  169.                 con = new SqlConnection(DBCon);  
  170.                 con.Open();  
  171.                 string query = string.Empty;  
  172.                 for (int i = 0; i < dsTemp.Tables.Count; i++)  
  173.                 {  
  174.                     rowsAffected = 0;  
  175.                     string colNames = string.Join(",", dsTemp.Tables[i].Columns.Cast<DataColumn>().Where(x => x.AutoIncrement == false).Select(x => x.ColumnName).ToArray<string>());  
  176.                     string[] arr = colNames.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);  
  177.                     query = "insert into " + dsTemp.Tables[i].TableName + "(" + colNames + ") values(";  
  178.                     for (int col = 0; col < arr.Length; col++)  
  179.                     {  
  180.                         if (col != arr.Length - 1)  
  181.                             query += "@" + arr[col] + ",";  
  182.                         else  
  183.                             query += "@" + arr[col] + ")";  
  184.                     }  
  185.                     cmd = new SqlCommand(query, con);  
  186.                     for (int row = 0; row < dsTemp.Tables[i].Rows.Count; row++)  
  187.                     {  
  188.                         for (int col = 0, arrCounter = 0; col < dsTemp.Tables[i].Columns.Count; col++)  
  189.                         {  
  190.                             if (!dsTemp.Tables[i].Columns[col].AutoIncrement)  
  191.                             {  
  192.                                 cmd.Parameters.AddWithValue("@" + arr[arrCounter], dsTemp.Tables[i].Rows[row][col].ToString());  
  193.                                 arrCounter++;  
  194.                             }  
  195.                         }  
  196.                         rowsAffected += cmd.ExecuteNonQuery();  
  197.                         cmd.Parameters.Clear();  
  198.                     }  
  199.                     Console.WriteLine("{0} Records Affected For Table: \"{1}\"", rowsAffected, dsTemp.Tables[i].TableName);  
  200.                 }  
  201.                 con.Close();  
  202.                 Console.WriteLine("Press any key to Terminate");  
  203.             }  
  204.             catch (Exception ex)  
  205.             {  
  206.                 Console.WriteLine(ex.Message);  
  207.             }  
  208.         }  
  209.   
  210.         static void Main(string[] args)  
  211.         {  
  212.             Program objProgram = new Program();  
  213.             objProgram.ReadExcelFile();  
  214.             Console.ReadLine();  
  215.         }  
  216.     }  
  217. }  
The following will be the output for that.

output

sql output