Search code examples
c#excelsearchoffice-interop

How to search for merged cells in excel file


How do you search for merged cells in an excel document with c#?

I want to manipulate my merged cells in a consistent manner, but I have to know their address to do so.

I have hundreds of, for lack of a better word, tables in Excel and each have merged cells on top of them which I have to move and put to the right of each table.

To do this I need to know how to search for merged cells, and get the addresses of the merged cells with C#. I am currently using Interop.

Also if you think there are simpler ways, with basic excel capabilities within excel, please let me know.

thanks for any help.


Solution

  • If you were using the newer Office products that suport Office Open XML you could probably parse the xml and find the tags that represent merged cells

    The following is an example of a sheet with 2 cells one merged from a1-b1 and a single cell a2.

    There are a few commercial and possibly some open source solutions that would simplify the xml processing.

    <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="x14ac" xmlns:x14ac="http://schemas.microsoft.com/office/spreadsheetml/2009/9/ac">
        <dimension ref="A1:B2"/>
        <sheetViews>
            <sheetView tabSelected="1" workbookViewId="0">
                <selection activeCell="A2" sqref="A2"/>
            </sheetView>
        </sheetViews>
        <sheetFormatPr defaultRowHeight="15" x14ac:dyDescent="0.25"/>
        <sheetData>
            <row r="1" spans="1:2" x14ac:dyDescent="0.25">
                <c r="A1" s="1" t="s">
                    <v>0</v>
                </c>
                <c r="B1" s="1"/>
            </row>
            <row r="2" spans="1:2" x14ac:dyDescent="0.25">
                <c r="A2" t="s">
                    <v>1</v>
                </c>
            </row>
        </sheetData>
        <mergeCells count="1">
            <mergeCell ref="A1:B1"/>
        </mergeCells>
        <pageMargins left="0.7" right="0.7" top="0.75" bottom="0.75" header="0.3" footer="0.3"/>
    </worksheet>