import openpyxl as oxl
print("openpyxl Ver : ", oxl.__version__)
openpyxl Ver : 3.0.5
from openpyxl import Workbook, load_workbook
wb2 = load_workbook("주소록.xlsx")
print(wb2.sheetnames)
ws = wb2['두번째시트']
print(type(ws))
['Sheet', '두번째시트', 'Sheet1'] <class 'openpyxl.worksheet.worksheet.Worksheet'>
for row in ws.iter_rows():
for cell in row:
print(cell, cell.value)
<Cell '두번째시트'.A1> 이름 <Cell '두번째시트'.B1> 전화번호 <Cell '두번째시트'.A2> 홍길동 <Cell '두번째시트'.B2> 02-302-3333 <Cell '두번째시트'.A3> 김길동 <Cell '두번째시트'.B3> 010-222-3334 <Cell '두번째시트'.A4> toto <Cell '두번째시트'.B4> 010-222-3334 <Cell '두번째시트'.A5> None <Cell '두번째시트'.B5> 02-302-3333 <Cell '두번째시트'.A6> 홍길동 <Cell '두번째시트'.B6> 7777777
import pandas as pd
print(pd.__version__)
1.1.3
# 제일 처음 시트의 내용 불러온다.
dat = pd.read_excel("주소록.xlsx")
dat
시트명 | Sheet |
---|
# 시트를 지정해서 읽을 수 있음.
dat = pd.read_excel("주소록.xlsx", sheet_name="두번째시트")
dat
이름 | 전화번호 | |
---|---|---|
0 | 홍길동 | 02-302-3333 |
1 | 김길동 | 010-222-3334 |
2 | toto | 010-222-3334 |
3 | NaN | 02-302-3333 |
4 | 홍길동 | 7777777 |
for idx, row in dat.iterrows():
print(idx, row[0], row[1])
0 홍길동 02-302-3333 1 김길동 010-222-3334 2 toto 010-222-3334 3 nan 02-302-3333 4 홍길동 7777777
### 원본 내용 백업
dat_ori = dat.copy()
dat.loc[ dat['이름'].isnull() , "이름체크" ] = "NOK"
dat.loc[ dat['이름'].notnull() , "이름체크" ] = "OK"
dat
이름 | 전화번호 | 이름체크 | |
---|---|---|---|
0 | 홍길동 | 02-302-3333 | OK |
1 | 김길동 | 010-222-3334 | OK |
2 | toto | 010-222-3334 | OK |
3 | NaN | 02-302-3333 | NOK |
4 | 홍길동 | 7777777 | OK |
# 2,3글자 숫자-3,4글자 숫자-4글자 숫자
dat['전화번호'].str.contains('\d{2,3}-\d{3,4}-\d{4}')
0 True 1 True 2 True 3 True 4 False Name: 전화번호, dtype: bool
# 전화번호 확인
ch_tel = dat['전화번호'].str.contains('\d{2,3}-\d{3,4}-\d{4}')
dat.loc[ ch_tel , "전화번호체크" ] = "OK"
dat.loc[ ~ch_tel , "전화번호체크" ] = "NOK"
dat
이름 | 전화번호 | 이름체크 | 전화번호체크 | |
---|---|---|---|---|
0 | 홍길동 | 02-302-3333 | OK | OK |
1 | 김길동 | 010-222-3334 | OK | OK |
2 | toto | 010-222-3334 | OK | OK |
3 | NaN | 02-302-3333 | NOK | OK |
4 | 홍길동 | 7777777 | OK | NOK |
# engine : 쓰기를 위해 사용하는 엔진.
writer = pd.ExcelWriter("주소록_chk.xlsx", engine='openpyxl')
dat_ori.to_excel(writer, sheet_name="sheet_ori")
dat.to_excel(writer, sheet_name="sheet_chk")
writer.save()