Many a times, we need to generate Excel reports as output from Windows applications. There are now 2 ways to do this:
- Using Office interop
- Using Open XML SDK
To be clear, Open XML is the recommended approach for working with Office applications using .Net. However, there are still many systems that rely heavily on Interop for this so in this post, I will be talking using the Interop approach to work with Excel. Specifically, let’s look at how we can merge a collection of cells and center them through .Net.
To accomplish this, we need to perform 3 steps, and they are as easy as they come – each step requires a single line of code in C#. So let’s take a look at the steps involved:
- Get an Excel range – For folks familiar with Excel interop, they would be aware that for most operations we would need to get our hands on an Excel Range object and then perform the intended operation on the range. Here is how we can create a Range object
Microsoft.Office.Interop.Excel.Range range = excelApp.get_Range(sheet.Cells[startRowIndex, startColumnIndex], sheet.Cells[endRowIndex, endColumnIndex]);
Here, excelApp refers to an instance of Microsoft.Office.Interop.Excel.Application class. The parameters that we need to pass to the get_Range() specify where we want the range to start and where it should end.
- Merge the cells – Once we have the handle to the range, we can call the Merge() on the range to do just that – merge the cells that form the range into a single cell
(Warning – there might be data loss if multiple cells within the range have different values)
- Center the cells – Finally, we need to set the alignment of the data in the merged cells so that data appears centered horizontally. This can be done again with a single statement as shown below
range.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignCenter;
So there you have it, we can put these 3 steps into a method and use it whenever we want to merge and center cells. One more thing we need to do is add a reference to Microsoft.Office.Interop.Excel.dll and import the same DLL to be able to use the Excel Interop API.