프로그래밍/Tips [IA]

[IA] C# Word automation 테이블 병합 셀의 개수 파악

nanze 2025. 2. 25. 15:11
반응형
 
 

개요

Word 문서에서 테이블의 특정 셀이 병합되었는지 확인하고, 병합된 경우 병합된 행과 열의 수를 계산하려면 다음 단계를 따릅니다:

  1. Word 문서를 열고 특정 테이블을 선택합니다.
  2. 확인하고자 하는 셀을 지정합니다.
  3. 셀이 병합되었는지 확인합니다.
  4. 병합된 경우, 병합 범위를 분석하여 행과 열의 수를 계산합니다.
using System;
using Word = Microsoft.Office.Interop.Word;

public class WordAutomation
{
    public void GetMergedCellInfo(string filePath, int tableIndex, int rowIndex, int columnIndex)
    {
        // Word 애플리케이션 인스턴스 생성
        Word.Application wordApp = new Word.Application();
        Word.Document doc = null;

        try
        {
            // Word 문서 열기
            doc = wordApp.Documents.Open(filePath);
            // 지정된 테이블 선택 (인덱스는 1부터 시작)
            Word.Table table = doc.Tables[tableIndex];

            // 특정 셀 선택
            Word.Cell cell = table.Cell(rowIndex, columnIndex);

            // 병합 여부 확인 및 병합 범위 계산
            if (cell.ColumnIndex == columnIndex && cell.RowIndex == rowIndex)
            {
                // 병합되지 않은 셀
                Console.WriteLine("이 셀은 병합되지 않았습니다.");
            }
            else
            {
                // 병합된 셀의 시작점과 끝점 계산
                int startRow = cell.RowIndex;
                int startColumn = cell.ColumnIndex;
                int endRow = startRow;
                int endColumn = startColumn;

                // 병합된 행의 끝점 찾기
                while (endRow < table.Rows.Count && 
                       table.Cell(endRow + 1, startColumn).ColumnIndex == startColumn)
                {
                    endRow++;
                }

                // 병합된 열의 끝점 찾기
                while (endColumn < table.Columns.Count && 
                       table.Cell(startRow, endColumn + 1).RowIndex == startRow)
                {
                    endColumn++;
                }

                // 병합된 행과 열의 수 계산
                int mergedRows = endRow - startRow + 1;
                int mergedColumns = endColumn - startColumn + 1;

                Console.WriteLine($"이 셀은 {mergedRows}개의 행과 {mergedColumns}개의 열로 병합되었습니다.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine($"오류 발생: {ex.Message}");
        }
        finally
        {
            // 자원 정리
            if (doc != null)
            {
                doc.Close();
            }
            if (wordApp != null)
            {
                wordApp.Quit();
            }
        }
    }

    // 사용 예시
    public static void Main()
    {
        WordAutomation wa = new WordAutomation();
        string filePath = @"C:\path\to\your\document.docx";
        wa.GetMergedCellInfo(filePath, 1, 1, 1); // 첫 번째 테이블의 (1,1) 셀 확인
    }
}

코드 설명


  • 매개변수:
    • filePath: Word 문서의 파일 경로.
    • tableIndex: 문서 내 테이블 번호 (1부터 시작).
    • rowIndex: 확인하고자 하는 셀의 행 번호.
    • columnIndex: 확인하고자 하는 셀의 열 번호.
  • 셀 병합 여부 확인:
    • cell.RowIndexcell.ColumnIndex가 입력값과 일치하면 병합되지 않은 셀로 판단합니다.
    • 그렇지 않으면 병합된 셀로 간주하고 범위를 계산합니다.
  • 병합 범위 계산:
    • 병합된 행의 수는 셀의 시작 행에서 끝 행까지 탐색하며 계산합니다.
    • 병합된 열의 수는 셀의 시작 열에서 끝 열까지 탐색하며 계산합니다.
    • while 루프를 사용해 병합된 범위의 경계를 찾습니다.
  • 자원 관리:
    • try-catch 블록으로 예외를 처리하며, finally 블록에서 Word 문서와 애플리케이션을 안전하게 종료합니다.
반응형