Skip to content

Latest commit

 

History

History
328 lines (274 loc) · 9.59 KB

220217.md

File metadata and controls

328 lines (274 loc) · 9.59 KB

Day 125

업무자동화(RPA)

엑셀 자동화

파일과 시트 생성 및 파일 저장

from openpyxl import Workbook

wb = Workbook()             # 새 워크북 생성
ws = wb.active              # 현재 활성화된 sheet 가져옴
ws.title = 'First_Sheet'    # sheet의 이름을 변경
wb.save('sample.xlsx')      # 파일 저장
wb.close()

위 코드를 실행하면 'First_Sheet'라는 이름을 가진 sheet를 가진 xlsx 파일이 만들어진다.

1_

시트 기본

from openpyxl import Workbook
wb = Workbook()
ws = wb.create_sheet()  # 새로운 sheet 기본 이름으로 생성
ws.title = 'MySheet'    # Sheet 이름 변경
ws.sheet_properties.tabColor = 'ff66ff' # RGB 형태로 값을 넣어주면 탭 색상 변경

ws1 = wb.create_sheet('YourSheet') # 주어진 이름으로 Sheet 생성
ws2 = wb.create_sheet('NewSheet', 2) # index 2에 Sheet 생성

new_ws = wb['NewSheet'] # Dict 형태로 Sheet에 접근

print(wb.sheetnames)    # 모든 Sheet 이름 확인

# Sheet 복사
new_ws['A1'] = 'Test'
target = wb.copy_worksheet(new_ws)
target.title = 'Copied Sheet'

wb.save('sample.xlsx')

['Sheet', 'MySheet', 'NewSheet', 'YourSheet']

워크시트의 인덱스는 0부터 시작한다.

셀 기본

2_

from openpyxl import Workbook
from random import *

wb = Workbook()
ws = wb.active

ws.title = 'Tea'

# 셀에 값을 입력
ws['A1'] = 1
ws['A2'] = 2
ws['A3'] = 3

ws['B1'] = 4
ws['B2'] = 5
ws['B3'] = 6

print(ws['A1'])          # 셀의 정보를 출력
print(ws['A1'].value)    # 셀의 값을 출력
print(ws['A10'].value)   # 값이 없을 땐 'None'을 출력 

# row = 1, 2, 3, ...
# column = A(1), B(2), C(3), ...
print(ws.cell(row=1, column=1).value) # ws['A1'].value
print(ws.cell(column=2, row=1).value) # ws['B1'].value

c = ws.cell(column=3, row=1, value=10)    # ws['C1'].value = 10
print(c.value) # ws['C1']

# 반복문을 이용해서 숫자 채우기
index = 1
for x in range(1, 11): # 10개 row
    for y in range(1, 11): # 10개 column
        # ws.cell(row=x, column=y, value=randint(0, 100)) # 0~100 사이의 숫자
        ws.cell(row=x, column=y, value=index)
        index += 1
wb.save('sample.xlsx')

<Cell 'Tea'.A1>
1
None
1
4
10

.cell의 row와 column은 순서가 바뀌어도 명시만 해주면 된다.

3_

파일 열기

from openpyxl import load_workbook

wb = load_workbook('sample.xlsx') # sample.xlsx 파일 불러오기
ws = wb.active

# cell 데이터 불러오기
for x in range(1, 11):
    for y in range(1, 11):
        print(ws.cell(row=x, column=y).value, end=' ') # 1 2 3 4 ..
    print()

# cell 갯수를 모를 때
for x in range(1, ws.max_row + 1):
    for y in range(1, ws.max_column + 1):
        print(ws.cell(row=x, column=y).value, end=' ')
    print()

1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100
1 2 3 4 5 6 7 8 9 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32 33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48 49 50
51 52 53 54 55 56 57 58 59 60
61 62 63 64 65 66 67 68 69 70
71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90
91 92 93 94 95 96 97 98 99 100

셀 영역 1

from openpyxl import Workbook
from openpyxl.utils.cell import coordinate_from_string
from random import *

wb = Workbook()
ws = wb.active

# 1줄씩 데이터 넣기
ws.append(['번호', '영어', '수학'])
for i in range(1, 11): # 데이터 10개 넣기
    ws.append([i, randint(0, 100), randint(0, 100)])

# (1)
print('=' * 10 + '(1)' + '=' * 10)
col_B = ws['B'] # 영어 column만 가져오기
print(col_B)
for cell in col_B:
    print(cell.value, end=' ')
print()

# (2)
print('=' * 10 + '(2)' + '=' * 10)
col_range = ws['B:C'] # 영어, 수학 column 함께 가지고 오기
for cols in col_range:
    for cell in cols:
        print(cell.value, end=' ')
    print()

# (3)
print('=' * 10 + '(3)' + '=' * 10)
row_title = ws[1] # 1 번째 row만 가지고 오기
for cell in row_title:
    print(cell.value, end=' ')
print()

# (4)
print('=' * 10 + '(4)' + '=' * 10)
row_range = ws[2:6] # 2번째 줄에서 6번째 줄까지 가지고 오기
for rows in row_range:
    for cell in rows:
        print(cell.value, end=' ')
    print()

# (5)
print('=' * 10 + '(5)' + '=' * 10)
row_range = ws[2:ws.max_row] # 2번째 줄부터 마지막 줄까지
for rows in row_range:
    for cell in rows:
        print(cell.coordinate, end=' ') # coordinate를 사용하면 셀의 좌표정보까지 가져올 수 있다.
        xy = coordinate_from_string(cell.coordinate)
        print(xy, end=' ')
    print()

# (6)
print('=' * 10 + '(6)' + '=' * 10)
print(xy[0])

wb.save('sample.xlsx')

==========(1)==========
(<Cell 'Sheet'.B1>, <Cell 'Sheet'.B2>, <Cell 'Sheet'.B3>, <Cell 'Sheet'.B4>, <Cell 'Sheet'.B5>, <Cell 'Sheet'.B6>, <Cell 'Sheet'.B7>, <Cell 'Sheet'.B8>, <Cell 'Sheet'.B9>, <Cell 'Sheet'.B10>, <Cell 'Sheet'.B11>)
영어 25 8 69 57 4 10 40 23 59 30
==========(2)==========
영어 25 8 69 57 4 10 40 23 59 30
수학 20 68 54 60 44 73 35 63 60 89
==========(3)==========
번호 영어 수학
==========(4)==========
1 25 20
2 8 68
3 69 54
4 57 60
5 4 44
==========(5)==========
A2 ('A', 2) B2 ('B', 2) C2 ('C', 2)
A3 ('A', 3) B3 ('B', 3) C3 ('C', 3)
A4 ('A', 4) B4 ('B', 4) C4 ('C', 4)
A5 ('A', 5) B5 ('B', 5) C5 ('C', 5)
A6 ('A', 6) B6 ('B', 6) C6 ('C', 6)
A7 ('A', 7) B7 ('B', 7) C7 ('C', 7)
A8 ('A', 8) B8 ('B', 8) C8 ('C', 8)
A9 ('A', 9) B9 ('B', 9) C9 ('C', 9)
A10 ('A', 10) B10 ('B', 10) C10 ('C', 10)
A11 ('A', 11) B11 ('B', 11) C11 ('C', 11)
==========(6)==========
C

python의 slicing과 다르게 여기서는 뒤의 숫자까지 포함해서 가져온다.

coordinate_from_string을 사용하면 A1을 A와 1로 행과 열을 분리시켜주는 역할을 한다.

5_

셀 영역 2

# 전체 rows
print(tuple(ws.rows))    # 한 줄씩 튜플로 가져옴 (A1, B1, C1)
for row in tuple(ws.rows):
    print(row[1].value)


# 전체 columns
print(tuple(ws.columns)) # (A1, A2, A3, ...)
for column in tuple(ws.columns):
    print(column[0].value)

for row in ws.iter_rows():    # 전체 row에 대해 반복
    print(row[2])

for column in ws.iter_cols(): # 전체 column
    print(column[0].value)

# 2번째 줄부터 11번째 줄까지, 2번째 열부터 3번째 열까지
for row in ws.iter_rows(min_row=2, max_row=11, min_col=2, max_col=3):
    print(row[0].value, row[1].value) # 수학, 영어

((<Cell 'Sheet'.A1>, <Cell 'Sheet'.B1>, <Cell 'Sheet'.C1>), (<Cell 'Sheet'.A2>, <Cell 'Sheet'.B2>, <Cell 'Sheet'.C2>), (<Cell 'Sheet'.A3>, <Cell 'Sheet'.B3>, <Cell 'Sheet'.C3>), (<Cell 'Sheet'.A4>, <Cell 'Sheet'.B4>, <Cell 'Sheet'.C4>), (<Cell 'Sheet'.A5>, <Cell 'Sheet'.B5>, <Cell 'Sheet'.C5>), (<Cell 'Sheet'.A6>, <Cell 'Sheet'.B6>, <Cell 'Sheet'.C6>), (<Cell 'Sheet'.A7>, <Cell 'Sheet'.B7>, <Cell 'Sheet'.C7>), (<Cell 'Sheet'.A8>, <Cell 'Sheet'.B8>, <Cell 'Sheet'.C8>), (<Cell 'Sheet'.A9>, <Cell 'Sheet'.B9>, <Cell 'Sheet'.C9>), (<Cell 'Sheet'.A10>, <Cell 'Sheet'.B10>, <Cell 'Sheet'.C10>), (<Cell 'Sheet'.A11>, <Cell 'Sheet'.B11>, <Cell 'Sheet'.C11>))
영어
76
66
12
26
20
79
33
42
47
72
((<Cell 'Sheet'.A1>, <Cell 'Sheet'.A2>, <Cell 'Sheet'.A3>, <Cell 'Sheet'.A4>, <Cell 'Sheet'.A5>, <Cell 'Sheet'.A6>, <Cell 'Sheet'.A7>, <Cell 'Sheet'.A8>, <Cell 'Sheet'.A9>, <Cell 'Sheet'.A10>, <Cell 'Sheet'.A11>), (<Cell 'Sheet'.B1>, <Cell 'Sheet'.B2>, <Cell 'Sheet'.B3>, <Cell 'Sheet'.B4>, <Cell 'Sheet'.B5>, <Cell 'Sheet'.B6>, <Cell 'Sheet'.B7>, <Cell 'Sheet'.B8>, <Cell 'Sheet'.B9>, <Cell 'Sheet'.B10>, <Cell 'Sheet'.B11>), (<Cell 'Sheet'.C1>, <Cell 'Sheet'.C2>, <Cell 'Sheet'.C3>, <Cell 'Sheet'.C4>, <Cell 'Sheet'.C5>, <Cell 'Sheet'.C6>, <Cell 'Sheet'.C7>, <Cell 'Sheet'.C8>, <Cell 'Sheet'.C9>, <Cell 'Sheet'.C10>, <Cell 'Sheet'.C11>))
번호
영어
수학
<Cell 'Sheet'.C1>
<Cell 'Sheet'.C2>
<Cell 'Sheet'.C3>
<Cell 'Sheet'.C4>
<Cell 'Sheet'.C5>
<Cell 'Sheet'.C6>
<Cell 'Sheet'.C7>
<Cell 'Sheet'.C8>
<Cell 'Sheet'.C9>
<Cell 'Sheet'.C10>
<Cell 'Sheet'.C11>
번호
영어
수학
76 83
66 80
12 53
26 75
20 86
79 84
33 97
42 24
47 97
72 33

min_row는 지정하지 않으면 가장 앞에 있는 row에서 시작하고, max_row는 그 반대다.

5_1

찾기

from openpyxl import load_workbook

wb = load_workbook('sample.xlsx')
ws = wb.active

for row in ws.iter_rows(min_row=2):
    # 번호, 영어, 수학
    if int(row[1].value) > 70:
        print(row[0].value, '번 학생은 영어 점수가 70보다 높습니다.')

# '영어'를 찾아서 '컴퓨터'로 바꿈
for row in ws.iter_rows(max_row=1):
    for cell in row:
        if cell.value == '영어':
            cell.value = '컴퓨터'

wb.save('sample_modified.xlsx')

1 번 학생은 영어 점수가 70보다 높습니다.
6 번 학생은 영어 점수가 70보다 높습니다.
10 번 학생은 영어 점수가 70보다 높습니다.

6_