C#에서 Excel 셀 병합 방법

발행: (2025년 12월 12일 오후 06:49 GMT+9)
4 min read
원문: Dev.to

Source: Dev.to

Prerequisites

시작하기 전에 다음이 설치되어 있는지 확인하세요:

  • Visual Studio가 머신에 설치되어 있어야 합니다.
  • Spire.XLS가 설치되어 있어야 합니다. 공식 사이트에서 다운로드하거나 Visual Studio의 NuGet을 통해 설치할 수 있습니다.

NuGet을 통해 Spire.XLS를 설치하려면:

  1. Visual Studio에서 NuGet Package Manager를 엽니다.
  2. Spire.XLS를 검색하고 Install를 클릭합니다.

준비가 완료되었습니다.

Setting Up Your Project

  1. Visual Studio에서 새 Console Application 프로젝트를 만듭니다.

    • Visual Studio를 엽니다.
    • Create a new project를 선택합니다.
    • **Console App (.NET Core)**를 선택합니다.
    • 프로젝트 이름을 지정합니다(예: MergeCellsInExcel).
    • Create를 클릭합니다.
  2. NuGet Package Manager를 통해 프로젝트에 Spire.XLS 라이브러리를 추가합니다.

Writing the Code to Merge Cells in Excel Using C#

다음은 셀을 병합하는 간단한 예제입니다:

using System;
using Spire.Xls;

namespace MergeCellsExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a new Workbook
            Workbook workbook = new Workbook();

            // Access the first worksheet
            Worksheet sheet = workbook.Worksheets[0];

            // Set some data in the cells
            sheet.Range["A1"].Text = "Merged Cells Example";
            sheet.Range["A2"].Text = "This is a sample cell content.";

            // Merge cells from A1 to D1
            sheet.Range["A1:D1"].Merge();

            // Format the merged cell
            sheet.Range["A1"].CellStyle.HorizontalAlignment = HorizontalAlignType.Center;
            sheet.Range["A1"].CellStyle.VerticalAlignment = VerticalAlignType.Center;
            sheet.Range["A1"].CellStyle.Font.IsBold = true;
            sheet.Range["A1"].CellStyle.Font.Size = 14;

            // Save the workbook to a file
            workbook.SaveToFile("MergedCellsExample.xlsx", ExcelVersion.Version2013);

            Console.WriteLine("Excel file with merged cells created successfully!");
        }
    }
}

Explanation of the Code

Creating a Workbook

Workbook workbook = new Workbook();

새 Excel 워크북을 초기화합니다.

Accessing the Worksheet

Worksheet sheet = workbook.Worksheets[0];

워크북의 첫 번째 워크시트를 가져옵니다.

Setting Data in Cells

sheet.Range["A1"].Text = "Merged Cells Example";

A1에 텍스트를 할당합니다.

Merging Cells

sheet.Range["A1:D1"].Merge();

범위 A1:D1을 하나의 셀로 병합합니다.

Formatting the Merged Cell

sheet.Range["A1"].CellStyle.HorizontalAlignment = HorizontalAlignType.Center;
sheet.Range["A1"].CellStyle.VerticalAlignment = VerticalAlignType.Center;
sheet.Range["A1"].CellStyle.Font.IsBold = true;
sheet.Range["A1"].CellStyle.Font.Size = 14;

텍스트를 가운데 정렬하고, 굵게 표시하며, 글꼴 크기를 14로 설정합니다.

Saving the Workbook

workbook.SaveToFile("MergedCellsExample.xlsx", ExcelVersion.Version2013);

Excel 2013 및 이후 버전과 호환되는 MergedCellsExample.xlsx 파일로 저장합니다.

Running the Code

프로젝트를 빌드하고 실행합니다. 프로그램이 지정된 대로 병합된 셀을 포함한 Excel 파일을 생성합니다. 파일을 Excel에서 열어 셀 병합 및 서식이 올바르게 적용되었는지 확인하세요.

Additional Tips

Merging Multiple Rows or Columns

셀 범위를 변경하면 여러 행이나 열을 병합할 수 있습니다. 예를 들어, 셀을 수직으로 병합하려면:

sheet.Range["A1:A5"].Merge();

Unmerging Cells

이전에 병합한 범위를 해제하려면:

sheet.Range["A1:D1"].UnMerge();

Formatting

Spire.XLS는 색상, 테두리 및 기타 스타일을 포함한 다양한 서식 옵션을 제공하므로 시각적으로 매력적인 Excel 문서를 만들 수 있습니다.

Conclusion

Excel에서 셀을 병합하는 것은 데이터를 정리하고 구조화된 보고서를 만드는 강력한 도구입니다. C#에서 Spire.XLS를 사용하면 애플리케이션 내에서 이 과정을 자동화할 수 있습니다. 위 예제는 동적 데이터 입력, 조건부 서식 또는 여러 시트에 걸친 자동화와 같은 기능을 확장할 수 있는 기본 토대를 제공합니다.

Back to Blog

관련 글

더 보기 »

C#에서 Excel을 HTML로 변환하는 방법

소개 웹에서 표 형식 데이터를 표시하는 것은 종종 어려울 수 있습니다. Excel 스프레드시트는 데이터 조직 및 분석에 강력하지만, 그들의 nativ...