Share via


Merge cells in Excel using C#

Question

Wednesday, May 8, 2013 11:45 PM

I am trying to merge cells using the Cells function. The code compiles,but the Excel spreadsheet that gets created doesn't have any merged cells. Assume ws is a _Worksheet. What am I doing wrong?

ws.Cells[1,1][2,2].Merge();

I thought this would merge the range "A1:B2," but it doesn't. Can you have two-dimensional Cells array? If so, what am I doing wrong? If not, why does the code compile?

Also, if instead of calling Merge I set the value of the two-dimensional array to "Hello world" then only cell B2 gets the hello world string. I expected the range A1:B2 to all get set to "Hello world." Why did this happen?

All replies (1)

Thursday, May 9, 2013 12:36 AM âś…Answered

I think if you used the Range object you'd get better results. Here's a code snippet of what you're looking for I think:

using Excel = Microsoft.Office.Interop.Excel;
using System.Reflection; 

Private void MergeCells()
{
    Excel.Application oXL;
        Excel._Workbook oWB;
        Excel._Worksheet ws;
        Excel.Range oRng;
        //Start Excel and get Application object.
        oXL = new Excel.Application();
    oXL.Visible = true;

        //Get a new workbook.
        oWB = (Excel._Workbook)(oXL.Workbooks.Add(Missing.Value));

        ws= (Excel._Worksheet)oWB.ActiveSheet;

        
    oRng = ws.get_Range("A1", "B2");
        oRng.Value2 = "Hello World";
        oRng.Merge(Missing.Value);
}

I think this link may be helpful to you: http://support.microsoft.com/kb/302084?wa=wsignin1.0

HTH