MoonNote

반응형
     

 

엑셀 파일

Cell Write Example File.xlsx
0.01MB

엑셀 파일 구성

예제 실행시 사용하였던 엑셀 파일 데이터 및 시트 정보

▪ 1행 5열 데이터셋

셀 데이터

 

Cell 값 쓰기(2가지 방법 : ¹['Cell'].value, ²cell(row=x, column=y).value)

import openpyxl

from openpyxl import load_workbook

# You must change the physical path before running this script.
currPath = "C:/Users/natio/OneDrive - 성균관대학교/99. Personal Blog/05. Python/05. OPENPYXL/02. Cell Example/"

# # Load the excel file
wb = openpyxl.load_workbook(filename=currPath+"Cell Write Example File.xlsx")
ws = wb.active

# Read Method 01 : ['Cell'].value
print('Initial A1 Value : ', ws['A1'].value)
# Read Method 02 : cell(row=x, column=y).value
print('Initial B1 Value : ', ws.cell(row=1,column=2).value)

# Write Method 01 : ['Cell'].value
ws['A1'].value = 111
# Write Method 02 : cell(row=x, column=y).value
ws.cell(row=1,column=2).value = 222

# Checking the changed cell value
# Read Method 01 : ['Cell'].value
print('Modified A1 Value : ', ws['A1'].value)
# Read Method 02 : cell(row=x, column=y).value
print('Modified B1 Value : ', ws.cell(row=1,column=2).value)

* ²cell(row=x, column=y).value에서 row와 column은 생략 가능 → cell(row=x, column=y).value를 cell(x, y).value로 사용해도 무방

 

Result

Initial A1 Value :  A
Initial B1 Value :  b
Modified A1 Value :  111
Modified B1 Value :  222

 

For문을 이용한 행, 열 Cell 값 쓰기

import openpyxl

from openpyxl import load_workbook

# You must change the physical path before running this script.
currPath = "C:/Users/natio/OneDrive - 성균관대학교/99. Personal Blog/05. Python/05. OPENPYXL/02. Cell Example/"

# # Load the excel file
wb = openpyxl.load_workbook(filename=currPath+"Cell Example File.xlsx")
ws = wb.active

# initialize row index
x = 0
# Result data
data = []

for i in range(5):
    x += 1
    y = 0
    W_data = []

    for j in range(5):
        y += 1
        
        ws.cell(x,y).value = 5*(x-1)+y
        CellData = ws.cell(x,y).value
        W_data.append(CellData)
    data.append(W_data)

# Excel 2D Data Array
print(data)

Result

[[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]]

 

 

Openpyxl 함수 모음

 

 

 

 

 

 

 

 

 

 

 

 

 

 

※ 이 글이 도움이 되었다면 "👆🏻구독"과 "🤍공감" 버튼을 클릭해주세요. 클릭 한번이 글 쓰는데 큰 힘이 됩니다.

 

 

 

공유하기

facebook twitter kakaoTalk kakaostory naver band