Merge cells excel interop

I have a database which contains 5 tables. Each table contains 24 rows and each row contains 4 columns.

I want to display these records in Excel sheet. The heading of each table is the name of the table, but I am unable to merge the columns for heading.

Please help me.

Philip Morton's user avatar

asked Feb 10, 2009 at 12:58

Using the Interop you get a range of cells and call the .Merge() method on that range.

eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge();

answered Feb 10, 2009 at 13:10

C. Ross's user avatar

C. RossC. Ross

30.8k42 gold badges145 silver badges235 bronze badges

2

oSheet.get_Range("A1", "AS1").Merge();

C. Ross's user avatar

C. Ross

30.8k42 gold badges145 silver badges235 bronze badges

answered Feb 6, 2013 at 4:30

Imamul Karim Tonmoy's user avatar

Excel.Application xl = new Excel.ApplicationClass();

Excel.Workbook wb = xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorkshe et);

Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

ws.Cells[1,1] = "Testing";

Excel.Range range = ws.get_Range(ws.Cells[1,1],ws.Cells[1,2]);

range.Merge(true);

range.Interior.ColorIndex =36;

xl.Visible =true;

Шыназ Алиш's user avatar

Шыназ Алиш

4012 gold badges6 silver badges23 bronze badges

answered Jul 13, 2015 at 9:05

Ahmad naser's user avatar

1

Code Snippet

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Excel.Application excelApp = null;
    private void button1_Click(object sender, EventArgs e)
    {
        excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
    }
}

Thanks

Mo Patel's user avatar

Mo Patel

2,3014 gold badges22 silver badges37 bronze badges

answered Aug 25, 2009 at 10:55

You can use Microsoft.Office.Interop.Excel:

worksheet.Range[worksheet.Cells[rowNum, columnNum], worksheet.Cells[rowNum, columnNum]].Merge();

You can also use NPOI:

var cellsTomerge = new NPOI.SS.Util.CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
_sheet.AddMergedRegion(cellsTomerge);

answered Jul 28, 2016 at 11:26

Sobhan's user avatar

SobhanSobhan

7461 gold badge9 silver badges31 bronze badges

This solves the issue in the appropriate way

// Merge a row
            ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
            ws.Range("B2:D3").Row(1).Merge();

answered Apr 8, 2016 at 17:55

Shalin Jirawla's user avatar

Shalin JirawlaShalin Jirawla

4791 gold badge5 silver badges24 bronze badges

You can use NPOI to do it.

Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

answered Aug 2, 2016 at 17:11

Ana Carolina Manzan's user avatar

Try it.

ws.Range("A1:F2").Merge();

answered May 18, 2019 at 1:35

Ly Thanh Ngo's user avatar

Ly Thanh NgoLy Thanh Ngo

3841 gold badge2 silver badges15 bronze badges

1

take a list of string as like

List<string> colValListForValidation = new List<string>();

and match string before the task. it will help you bcz all merge cells will have same value

answered Mar 17, 2015 at 14:01

Vipswelt's user avatar

VipsweltVipswelt

3451 gold badge2 silver badges6 bronze badges

Worksheet["YourRange"].Merge();

Adam's user avatar

Adam

4,3671 gold badge34 silver badges49 bronze badges

answered Apr 12, 2017 at 14:57

Subha8's user avatar

2

using Excel = Microsoft.Office.Interop.Excel;
// Your code...
yourWorksheet.Range[yourWorksheet.Cells[rowBegin,colBegin], yourWorksheet.Cells[yourWorksheet.rowEnd, colEnd]].Merge();

Row and Col start at 1.

answered Dec 27, 2019 at 23:47

Nguyen Van Thanh's user avatar

My simple solution would be with .Merge() method.

  • X — cell letter
  • Y — cell number
ws.Range["XY:XY"].Merge();

answered Jan 12 at 8:25

Ivan Sambol's user avatar

9 ответов

Используя Interop, вы получаете диапазон ячеек и вызываете метод .Merge() в этом диапазоне.

eWSheet.Range[eWSheet.Cells[1, 1], eWSheet.Cells[4, 1]].Merge();

C. Ross
10 фев. 2009, в 13:27

Поделиться

oSheet.get_Range("A1", "AS1").Merge();

Imamul Karim Tonmoy
06 фев. 2013, в 05:03

Поделиться

Excel.Application xl = new Excel.ApplicationClass();

Excel.Workbook wb = xl.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorkshe et);

Excel.Worksheet ws = (Excel.Worksheet)wb.ActiveSheet;

ws.Cells[1,1] = "Testing";

Excel.Range range = ws.get_Range(ws.Cells[1,1],ws.Cells[1,2]);

range.Merge(true);

range.Interior.ColorIndex =36;

xl.Visible =true;

Edit
13 июль 2015, в 10:08

Поделиться

Вы можете использовать NPOI для этого.

Workbook wb = new HSSFWorkbook();
Sheet sheet = wb.createSheet("new sheet");

Row row = sheet.createRow((short) 1);
Cell cell = row.createCell((short) 1);
cell.setCellValue("This is a test of merging");

sheet.addMergedRegion(new CellRangeAddress(
        1, //first row (0-based)
        1, //last row  (0-based)
        1, //first column (0-based)
        2  //last column  (0-based)
));

// Write the output to a file
FileOutputStream fileOut = new FileOutputStream("workbook.xls");
wb.write(fileOut);
fileOut.close();

Ana Carolina Manzan
02 авг. 2016, в 17:13

Поделиться

Фрагмент кода

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private Excel.Application excelApp = null;
    private void button1_Click(object sender, EventArgs e)
    {
        excelApp.get_Range("A1:A360,B1:E1", Type.Missing).Merge(Type.Missing);
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        excelApp = Marshal.GetActiveObject("Excel.Application") as Excel.Application ;
    }
}

Спасибо

Akshaya
25 авг. 2009, в 11:48

Поделиться

Worksheet["YourRange"].Merge();

Subha8
12 апр. 2017, в 15:12

Поделиться

Вы можете использовать Microsoft.Office.Interop.Excel:

worksheet.Range[worksheet.Cells[rowNum, columnNum], worksheet.Cells[rowNum, columnNum]].Merge();

Вы также можете использовать NPOI:

var cellsTomerge = new NPOI.SS.Util.CellRangeAddress(firstrow, lastrow, firstcol, lastcol);
_sheet.AddMergedRegion(cellsTomerge);

Sobhan
28 июль 2016, в 12:40

Поделиться

Это решает проблему соответствующим образом.

// Merge a row
            ws.Cell("B2").Value = "Merged Row(1) of Range (B2:D3)";
            ws.Range("B2:D3").Row(1).Merge();

Shalin Jirawla
08 апр. 2016, в 18:42

Поделиться

возьмите список строк как

List<string> colValListForValidation = new List<string>();

и сопоставить строку перед задачей. это поможет вам bcz все ячейки слияния будут иметь одинаковое значение

Vipswelt
17 март 2015, в 15:44

Поделиться

Ещё вопросы

  • 1Ext js 6.2 CORS не работает для магазина, объявленного в viewModel
  • 0Как передать целочисленные переменные из PHP в API Google Chart Javascript?
  • 1Запись изображения холста в видео файл с помощью recordrtc
  • 1Python 2 csv.DictWriter () Unicode Encode обработка исключений
  • 0Получить количество пользователей на основе другого столбца
  • 0Что означает класс *, когда я создаю запись CSS? [Дубликат]
  • 1CanExecute на Relay Command не работает
  • 0MySQL Workbench считывает BLOB, содержащий дату
  • 0Prestashop: добавить текст на странице оплаты заказа
  • 1Проблемы с Raycast для ARCamera в Unity3d с Vuforia SDK
  • 0При нажатии — получить кнопку нажата?
  • 0Как добавить пробелы к тексту при использовании .text ()
  • 0mysqli_connect убивает PHP-скрипт при запуске из веб-браузера
  • 0AngularJS — Как получить доступ к массиву Javascript?
  • 0центрирование выпадающего меню по вертикали
  • 0Настраиваемая URL-адресная схема Windows Azure Active Directory
  • 1Python ping список хостов IPv6 и со временем сделайте словарь доступных и недоступных хостов
  • 1Использование класса POCO в качестве класса домена, но с пользовательскими получателями и установщиками ссылок?
  • 1как отобразить JButton на заставке
  • 0Array глубокие часы в угловом представлении (HTML)
  • 1Каков наилучший способ обновить accessToken в приложении с новым accessToken?
  • 0Карты Google не отображаются при переходе назад и вперед по страницам приложения
  • 0как увеличить ширину элемента списка флажков
  • 1Проверка MAC представления состояния не удалась с server.transfer
  • 1Python — Извлечение текста в строке между двумя другими конкретными символами?
  • 1RCaller получит матрицу неизвестного размера
  • 1Элегантная ветвь (на любом языке)
  • 0ASP MVC: использование @Model в ng-repeat
  • 0Как включить одну HTML-страницу (в качестве заголовка) в другую HTML-страницу?
  • 1Вызов метода Java из суперкласса и изменение оператора возврата
  • 1Добавление Android в меню XML останавливает компиляцию приложения
  • 1Как я могу узнать список приложений, использующих определенную размещенную службу web / wcf?
  • 0Отображение @ManyToOne / Внешний ключ Hibernate Java
  • 0Удаление всех строк, которые не имеют никакой связи с зависимой таблицей
  • 0Проблема оператора SQL с поддержкой Postgresql в CakePHP 2.4.7 и TreeBehavior
  • 0Вертикальная укладка преобразованного текста с использованием Sass CSS и FlexBox
  • 1Получение NameError в Python при получении данных в Jupyter
  • 1Повторяющиеся записи в ответе сервера .net
  • 1Как я могу добавить значок счетчика в виджет?
  • 0преобразование jQuery в чистый javascript
  • 0Странная проблема с фиксированной прокруткой div
  • 1какую коллекцию использовать для данных типа один ко многим?
  • 0PHPMyadmin строка отображается по-разному в двоичном
  • 1Java GUI Paintcomponent (новичок)
  • 0Передайте файл байтов в программу C ++, через Linux и прочитайте побайтово?
  • 1Backbone — обновление моделей в коллекции с помощью данных, опрошенных из другого API
  • 0Как я могу перенаправить после проверки условия (если)? В php html или javascript
  • 1сам вызов метода onUpgrade
  • 1Использование Oauth для соединения приложения Java с приложением GAE

  • Raj


  • 11/17/2012 1:42 AM

  • C#.Net

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

  • Remove From My Forums
  • Question

  • Below code, I had done column is not merge help me to solve this problem

    private void button2_Click(object sender, EventArgs e)
            {
                String filetest = «C:\com\test.xlsx»;
                if (File.Exists(filetest))
                {
                    File.Delete(filetest);
                }
                Excel.Application oApp;
                Excel.Workbook oBook;
                Excel.Worksheet oSheet;

                oApp = new Excel.Application();
                oBook = oApp.Workbooks.Add();
                oSheet = (Excel.Worksheet)oBook.Worksheets.get_Item(1);
                Excel.Range c1 = oSheet.Cells[2, 1];
                Excel.Range c2 = oSheet.Cells[5, 1];
                Excel.Range oRange = oSheet.get_Range(c1, c2);
                oRange.Merge(true);
                oRange.VerticalAlignment = XlVAlign.xlVAlignCenter;
                oSheet.Cells[4, 1] = «SL.No»;

                oBook.SaveAs(filetest);
                oApp.Visible = true;
                // oBook.Close();
                // oApp.Quit();
                MessageBox.Show(«File Created»);
            }

                

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)

range.Merge(Type.Missing);

  • 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.

Solution 1

You can use this package it can do every thing for excel , it’s very easy for use.

NuGet Gallery | EPPlus 4.5.3.1[^]

e.g. if you want to export DataTable to Excel

using (ExcelPackage pck = new ExcelPackage(newFile))
{
  ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Accounts");
  ws.Cells["A1"].LoadFromDataTable(dataTable, true);
  pck.Save();
}

Comments

I’ll installed (EPPlus) this library and using below code:

using (var excel = new ExcelPackage(new System.IO.FileInfo(@»physical_address_of_your_xslx_file»)))
{
var sheet1 = excel.Workbook.Worksheets[«Sheet1»];
sheet1.Cells[«C2:C7»].Merge = true;
sheet1.Cells[«C2:C7»].Style.VerticalAlignment = OfficeOpenXml.Style.ExcelVerticalAlignment.Bottom;
sheet1.Cells[«C2»].Value = «The value»;

excel.Save();
}

But Its showing exceptional error: An unhandled exception of type ‘System.NullReferenceException’ occurred in ExportExcel.exe Additional information: Object reference not set to an instance of an object.

Merging cells means joining two or more separate cells into one large cell, which is useful when you need to create a label that spans multiple columns. In this article, we will demonstrate how to merge or unmerge cells in Excel in C# and VB.NET using Spire.XLS for .NET library.

  • Merge Cells in Excel in C# and VB.NET
  • Unmerge Cells in Excel in C# and VB.NET

Install Spire.XLS for .NET

To begin with, you need to add the DLL files included in the Spire.XLS for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.XLS

Merge Cells in Excel in C# and VB.NET

The following are the steps to merge cells in Excel:

  • Create a Workbook instance
  • Load the Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Access the specific range of cells and merge them into one using XlsRange.Merge() method.
  • Center the text in the merged cell by setting CellRange.Style.HorizontalAlignment property to HorizontalAlignType.Center.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace MergeCells
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("Sample.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];
            //Merge cells A1-D1 into one cell
            CellRange range = sheet.Range["A1:D1"];
            range.Merge();
            //Center the text in the merged cell
            range.Style.HorizontalAlignment = HorizontalAlignType.Center;            

            //Save the result file
            workbook.SaveToFile("MergeCells.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Merge or Unmerge Cells in Excel

Unmerge Cells in Excel in C# and VB.NET

The following are the steps to unmerge cells in Excel:

  • Create a Workbook instance
  • Load the Excel file using Workbook.LoadFromFile() method.
  • Get the desired worksheet using Workbook.Worksheets[sheetIndex] property.
  • Access the specific range of cells and unmerge them using XlsRange.UnMerge() method.
  • Save the result file using Workbook.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Xls;

namespace UnmergeCells
{
    class Program
    {
        static void Main(string[] args)
        {

            //Create a Workbook instance
            Workbook workbook = new Workbook();
            //Load the Excel file
            workbook.LoadFromFile("MergeCells.xlsx");

            //Get the first worksheet
            Worksheet sheet = workbook.Worksheets[0];
            //Unmerge cells A1-D1
            CellRange range = sheet.Range["A1:D1"];
            range.UnMerge();

            //Save the result file
            workbook.SaveToFile("UnMergeCells.xlsx", ExcelVersion.Version2013);
        }
    }
}

C#/VB.NET: Merge or Unmerge Cells in Excel

Apply for a Temporary License

If you’d like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Понравилась статья? Поделить с друзьями:
  • Merge cells and excel
  • Merge cell text excel
  • Merge and center excel
  • Merge all sheets in one excel
  • Merge all rows in excel