In my previous article I explained about how to create excel file, how to open excel file and how to read excel files. Today we discuss about how to Merge Excel cells in C#.
Microsoft.Office.Interop.Excel library providing the Merge() method to merge the Excel cells as shown below.
using System;
using System.Reflection;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;
using System.Diagnostics;
namespace CSharpMergeExcelCells
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Excel.Application oXL = new Excel.Application();
Excel.Workbook oWB = oXL.Workbooks.Open(Application.StartupPath + "\\Sample.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Excel.Worksheet oWS = oWB.Worksheets[1] as Excel.Worksheet;
//rename the Sheet name
oWS.Name = "Excel Sheet";
oWS.get_Range("A1", "D1").Merge(Type.Missing);
oWB.SaveAs(Application.StartupPath + "\\Sample1.xlsx", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, issing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Process.Start(Application.StartupPath + \\Sample1.xlsx);
}
}
}
As shown above first we are opening the Excel sheet located at Application.StartupPath and merging the excel cells range from A1 to D1 by using the Merge method. The output after running the application as shown below.
CSharpMergeExcelCells.zip (1.07 mb)
For Microsoft Office Promo Code Click here