Source : https://pypi.org/project/openpyxl/
Document : https://openpyxl.readthedocs.io/en/stable/index.html#
from openpyxl import Workbook, load_workbook
"""
1. 데이터 쓰기
"""
wb = Workbook() # 파일 생성
ws = wb.active # sheet 생성 및 활성화
ws = wb.create_sheet(title='new_sheet') # sheet 생성( sheet이름 지정 )
ws['a1'] = "이름" # cell에 값 입력
ws.cell(1, 2, "전화번호")
ws.append([1, 2, 3]) # active cell 다음 행에 행 단위로 추가
wb.save(r'C:\Users\neo21\OneDrive\바탕 화면\temp.xlsx') # 파일 저장
"""
2. 데이터 읽기
"""
wb = load_workbook(r'C:\Users\neo21\OneDrive\바탕 화면\temp.xlsx')
ws = wb['new_sheet']
print(ws['a1'].value)
print(ws.cell(2, 1).value)
cells = ws['a1:b2']
for i in cells:
print(i) # 행단위 투플 : (<Cell 'new_sheet'.A1>, <Cell 'new_sheet'.B1>)
for j in i:
print("%10s" % (j.value), end=" ")
print()
for i in ws.rows: # worksheet 행단위 모든 데이터
for r in i:
print("%10s" % (r.value), end=" ") # (<Cell 'new_sheet'.A1>, <Cell 'new_sheet'.B1>, <Cell 'new_sheet'.C1>)
print()
for i in ws.columns: # worksheet 열단위 모든 데이터
for c in i:
print("%10s" % (c.value), end=" ") # (<Cell 'new_sheet'.A1>, <Cell 'new_sheet'.B1>, <Cell 'new_sheet'.C1>)
print()
# 전체 데이터 행단위 리스트화 # [[row1...], [row2...]]
all_values = []
for row in ws.rows:
row_value = []
for cell in row:
row_value.append(cell.value)
all_values.append(row_value)
print(all_values)
"""
3. 파일저장
"""
wb.save(r'C:\Users\neo21\OneDrive\바탕 화면\temp.xlsx') # 파일 저장
'python package' 카테고리의 다른 글
Poetry를 이용한 패키지 관리 (0) | 2022.11.04 |
---|---|
gTTs 사용법 (0) | 2022.11.02 |
google trans 사용법 (0) | 2022.11.02 |