3
votes

I am trying to read an excel spreadsheet via open xml sdk with the following format and determine which 1st row merged cells corrpsond to the 2nd row.

How can I check if a cell is in a merged state?

------------------------------------------------------------
       Main Heading 1     |     Main heading 2              |
------------------------------------------------------------
Sub Head 1   | sub head 2 |     sub head 3                  |
-------------------------------------------------------------
             |            |                                 |
2

2 Answers

3
votes
const string testFileName = @"C:\Users\koo\Desktop\test\test\Test.xlsx";
string sheetName = "Sheet1";
using (SpreadsheetDocument document = SpreadsheetDocument.Open(testFileName, true))
{
    WorkbookPart wbPart = document.WorkbookPart;
    Sheet theSheet = wbPart.Workbook.Descendants<Sheet>().Where(s => s.Name == sheetName).FirstOrDefault();
    WorksheetPart wsPart = (WorksheetPart)(wbPart.GetPartById(theSheet.Id));
    MergeCells mcs = wsPart.Worksheet.Descendants<MergeCells>().First();

    var mcl = mcs.ChildElements.ToList();
    foreach (MergeCell mc in mcl)
    {

    }
    document.WorkbookPart.Workbook.Save();
}
2
votes

If you are using the ClosedXml library, then to check whether a cell is merged or not you can use the code given below.

XLWorkbook excelWorkBook = null;
excelWorkBook = new XLWorkbook(filePath);
var ws = excelWorkBook.Worksheet("Sheet1"); 
bool check= ws.Cell("Cell Name").IsMerged();

check will return true or false

Elizabeth