본문 바로가기

Python을 사용하여 Outlook과 Excel 연동하기(2) - 개발 본문

ETC

Python을 사용하여 Outlook과 Excel 연동하기(2) - 개발

00rigin 2021. 11. 25. 18:03

Outlook에서 학생들의 정보를 추출했으니, 엑셀 파일에 해당 학생의 퀴즈 제출 여부에 체크를 하면 된다.

 

먼저, 엑셀을 사용하기 위해서는 openpyxl 이라는 라이브러리를 사용해야한다.

 

from openyxl import load_workbook

을 사용하여 엑셀의 한 시트에 접근하여 작업을 할 수 있다.

 

1
2
3
4
5
from openpyxl import load_workbook # Exel API
wb = load_workbook(filename="test.xlsx"# 엑셀파일 오픈
sheet = wb.worksheets[0# 맨 앞에 시트 꺼내기
sheet['C4'= 'o' # 시트에 작성
wb.save("test.xlsx")
cs

 

위와 같이 엑셀 파일을 열고, 시트 인덱스에 따라 작성할 시트를 선택하고, 원하는 위치에 원하는 글자를 적을 수 있다.

 

sheet.row 를 통해 row별로 접근또한 가능하다. 아래처럼 이미 저장되어있는 내용이 있을때,

 

1
2
3
4
5
6
7
from openpyxl import load_workbook # Exel API
wb = load_workbook(filename="test.xlsx"# 엑셀파일 오픈
sheet = wb.worksheets[0# 맨 앞에 시트 꺼내기
for row in sheet.rows: # 엑셀 시트에서 
    print(row[2].value) # 확인
    
wb.save("test.xlsx")
cs

 

위와 같이 2번째 row의 값들만을 추출할 수 있다.

 

이를 통해 각 학생의 학번을 확인하고, 원하는 위치로 이동하여 'o' 를 입력하여 제출 여부를 작성할 수 있다.

 

가끔 학번을 이상하게 적어 제출하는 학생이 존재하므로, 그에 따른 예외처리를 추가하고

기한 내에 제출을 완료했는지 확인하는 부분을 추가하면 완성!

 

<전체 코드>

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
import win32com.client as cli #outlook API
from openpyxl import load_workbook # Exel API
 
# 찾는 문자 있으면 참 리턴
def findExistString(searchString, text):
    if searchString in text: return True
    elsereturn False
 
deadline = [[0 for x in range(3)]for y in range(13)]
deadline[8= ["9""2021-05-05 18:00:00""N"#챕터-마감일-엑셀 colum번호
deadline[9= ["10""2021-05-12 18:00:00""O"]
deadline[10= ["11""2021-05-19 18:00:00""P"]
deadline[11= ["12""2021-05-26 18:00:00""Q"]
deadline[12= ["13""2021-05-31 18:00:00""R"]
 
outlook = cli.Dispatch("Outlook.Application").GetNamespace("MAPI"# 아웃룩객체
inbox = outlook.GetDefaultFolder(6# 받은편지함에서 객체 가져옴
msg = inbox.Items #메세지 정보
msg_counter = msg.count # 총갯수
 
wb = load_workbook(filename="Quiz_2021_test.xlsx"# 엑셀파일 오픈
sheet = wb.worksheets[0# 맨 앞에 시트 꺼내기
 
= 1
valid = 0
count = 0
late_student = []
invalid_id_student = []
 
for ms in msg:
    if(ms.SenderName == "noreply-he-qa@mheducation.com"):
        count+=1
        article = ms.Body
        # 챕터넘버 확인
        chap_index = article.find("Chapter: Chapter ")
        student_index = article.find("Section ID: ")
        chap = article[chap_index+len("Chapter: Chapter ")]
        student_id = article[student_index+len("Section ID: ")]
        if(article[chap_index+len("Chapter: Chapter ")+1].isdigit()):
            chap=chap+article[chap_index+len("Chapter: Chapter ")+1]
        
        #학번
        for j in range(1,10):
            student_id = student_id+article[student_index+len("Section ID: ")+j]
            
        #### 엑셀 접근####
        if(student_id.isdigit()): # 학번 적은 애들만
            
            for j in range(8,13): #날짜와 챕터 맞는지 확인
                if(chap == deadline[j][0and str(ms.ReceivedTime)<=deadline[j][1]):# 챕터의 데드라인 확인
                    for row in sheet.rows: # 엑셀 시트에서 
                        if findExistString(student_id, str(row[2].value)): # 학번 찾기
                            pos = deadline[j][2]+str(row[3].row)
                            sheet[pos] = 'o' # 체크
                            valid+=1
                               
                elif(chap == deadline[j][0and str(ms.ReceivedTime)>deadline[j][1]): # 늦은 학생
                    late_student.append([student_id, chap, str(ms.ReceivedTime)])
 
        else# 학번 이상한 학생
            invalid_id_student.append(str(student_id))
    
    i=i+1
 
# 처리 정보 출력 
print("Sum : "+str(count))
print("# of valid mail : "+str(valid))
print("late_student : ", end='')
print(late_student)
print("invalid id student : ", end='')
print(invalid_id_student)
wb.save("Quiz_2021_test.xlsx")
    
cs

 

<결과>

빠밤~!

지긋지긋 했던 확인 작업도 끝!

Comments