본문 바로가기
프로그래밍 언어/C#

[C#] 엑셀(Excel) - 글자 색상 변경

by Jinwood 2024. 3. 18.
반응형

C#으로 엑셀에 접근하여 글자를 생성하다 보면 특정 셀의 글자색을 변경하거나, 셀의 특정 부분의 글자 색을 변경해야 할 때가 있다. 그럴 때 코드로 정의하는 방법을 알아보았다.

 

Excel의 셀에 접근하기 위해서는 우선 Excel Sheet를 정의해야한다. Excel Sheet 정의는 아래와 같으며, Application -> Workbook -> Worksheet 순서로 생성한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
using NetOffice.OfficeApi;
using Excel = NetOffice.ExcelApi;
 
private static bool Create_Worksheet()
{
    string path = "C:\Example.xlsx";
    string sheetName = "예제";
    
    Excel.Application xlApp = new Excel.Application();
    Excel.Workbook xlwb = xlApp.Workbooks.Open(path);
    Excel.Worksheet xlsh = (Excel.Worksheet)xlwb.Worksheets[sheetName];
 
}
cs

 

1. 셀 전체의 색상 변경

위 설정한 Worksheet에서 특정 셀에 대하여 색상을 설정한다. Worksheet를 설정했을 때와 같이 Worksheet 내부의 셀(Cell)에 접근하고, 해당 셀의 Font 속성의 Color를 정의하는 방식이다.

Worksheet의 0 번째 페이지에 (10,0) 번째 셀의 글자를 빨강색으로 변경하는 코드이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using NetOffice.OfficeApi;
using Excel = NetOffice.ExcelApi;
using System.Drawing;
 
public void Set_Cell_Color(Excel.Worksheet xlsh)
{
    int page = 0;
    
    int row = 10;
    int column = 0;
 
    xlsh[page].Cells[row, column].Font.Color = Color.Red;
}
 
cs

 

2. 셀의 특정 문자의 색상 변경

1번에서 특정 셀에 대하여 글자 색상을 변경하였다면, 이번에는 특정 글자를 변경하는 코드를 알아보자. 특정 글자를 찾아내어 변경하는 것은 아니고, 입력한 n번째 글자부터 몇 개까지 색상을 설정할 것인지 정의하는 것이다.

아래 코드는 위의 (10,0)번째 셀에 작성된 글자가 "This is Example" 이라면, "This" 부분만 빨간색으로 변경하는 코드이다. This는 전체 문자열에서 0번째 글자부터 4개로 볼 수 있다. 해당 셀을 정의하는 코드는 동일하며, Characters() 속성을 통해 특정 문자에 대한 설정을 적용할 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using NetOffice.OfficeApi;
using Excel = NetOffice.ExcelApi;
using System.Drawing;
 
public void Set_Cell_Color(Excel.Worksheet xlsh)
{
    int page = 0;
    
    int row = 10;
    int column = 0;
 
    xlsh[page].Cells[row, column].Characters(0,4).Font.Color = ColorTranslator.ToOle(Color.Red);
}
 
cs

 

3. 추가 - 강조 표시(Bold) 방법

색상까지 변경했다면 글자를 굵게 표시하여 강조하고 싶을 수 있다. 그럴 때 Bold 속성을 사용하면 되고, 코드는 앞서 설명한 코드와 유사하다. 다만 Bold 속성은 true/false로 설정한다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
using NetOffice.OfficeApi;
using Excel = NetOffice.ExcelApi;
using System.Drawing;
 
public void Set_Cell_Color(Excel.Worksheet xlsh)
{
    int page = 0;
    
    int row = 10;
    int column = 0;
 
    // 셀 전체 Bold 처리
    xlsh[page].Cells[row, column].Font.Bold = true;
 
    // 셀의 일부 글자만 Bold 처리
    xlsh[page].Cells[row, column].Characters(0,4).Font.Bold = true;
}
 
cs

 

 

끝!

 

 

반응형

댓글