Python/라이브러리

파이썬 (python) 라이브러리 - openpyxl, xlrd (excel 다루기)

snowman95 2021. 3. 9. 23:12
728x90
반응형

openpyxl

- Document : openpyxl.readthedocs.io/en/stable/

 

pip install openpyxl


from openpyxl import Workbook

wb = Workbook(filename)	          새 excel 파일 생성 하여 ws 반환
wb = load_workbook(filename)      기존 excel 파일 로드
wb = load_workbook(filename, data_only=True) 수식이 아닌 값으로 받아온다.

ws = wb.active                    활성화된 시트 선택 (기본시트 선택됨)
ws = wb[sheet_title]              시트 이름으로 시트 선택
ws = wb.create_sheet(sheet_title) 시트 생성
ws.title = sheet_title            시트 이름 지정
wb.save("C:/파일위치.xlsx") excel  excel 파일 저장



ws.append([1,2,3])                행 단위로 입력
ws.cell(5, 5, '입력값')           셀 단위로 입력
ws['A1'] = '입력값'               특정 좌표에 입력

ws['B2'].value                    셀 주소로 값 가져오기
ws.cell(3, 2).value               셀 좌표로 값 가져오기 
ws['B3' : 'B6']                   연속된 셀 주소 선택

ws.rows	                          열 단위로 가져오기
ws.columns                        행 단위로 가져오기

for row in load_ws.rows:          모든 행 단위로 출력
     print(row)
     
for column in load_ws.columns:    모든 열 단위로 출력
     print(column)

for row in load_ws.rows:          열 단위로 반복하면서 셀 값 가져오기 
	for cell in row: 
        print(cell.value)
        
for column in load_ws.columns:    행 단위로 반복하면서 셀 값 가져오기 
	for cell in column: 
        print(cell.value)


all_values = []                   모든 행/열 리스트로 가져오기
for row in load_ws.rows: 
     row_value = [] 
     for cell in row: 
          row_value.append(cell.value) 
     all_values.append(row_value)
print(all_values) 

pandas.DataFrame 과 같이 사용 가능

df 받아서 워크시트에 출력
def convert_df_to_ws(df, ws):
	for r in dataframe_to_rows(df, index=True, header=True):
    	ws.append(r)
    return ws


워크시트 받아서 df로 반환
def convert_ws_to_df(df, ws, include_index_or_columns):
	if include_index_or_columns:
		data = ws.values
		cols = next(data)[1:]
		data = list(data)
		idx = [r[0] for r in data]
		data = (islice(r, 1, None) for r in data)
		df = DataFrame(data, index=idx, columns=cols)
	else:
		df = DataFrame(ws.values)
	return df

 

 

 

xlrd 

import sys 
import subprocess
try: import re
except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", 're'])
finally: import re
try: import xlrd
except ImportError: subprocess.check_call([sys.executable, "-m", "pip", "install", 'xlrd'])
finally: import xlrd

workbook = xlrd.open_workbook(r'액셀명.xlsx')
sheet = workbook.sheet_by_name("시트명")

sheet.cell_value(row_num, 4)

 

 

반응형