Skip to content
컴퓨터잡담
2021.07.19 12:03

파이썬 엑셀 다루기 - openpyxl 사용법

조회 수 4906 추천 수 0 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄
?

단축키

Prev이전 문서

Next다음 문서

크게 작게 위로 아래로 댓글로 가기 인쇄

 

 

 

https://theheydaze.tistory.com/126

 

설치방법

pip install openpyxl

OpenPyXL sheet 열기 사용법

 

  1) import 모듈명

    - openpyxl

 

  2) 파일 열기 

    - openpyxl.load_workbook('파일명')

Ex) wb = openpyxl.load_workbook('./test.xlsx')

 

  3) 파일 닫기

    - close()

Ex) wb.close()

 

  3) sheet 열기 

    (1) index를 sheet이름으로하여 찾기(이게 더 좋다)

  - wb['sheet1'] 

  

    (2) get_sheet_by_name('Sheet1') 함수 이용(비 추천 pychame에서 경고 발생)

  - sheet = wb.get_sheet_by_name('Sheet1')

  

  4) 현재 열린 sheet를 열기

    - wb.actvie

Ex) sheet = wb.actvie

 

 

5. OpenPyXL cell 조작 사용법

 

  1) cell 접근 방법

    - sheet = wb['Sheet1'] 를 통해 우선 sheet 정보를 얻는다.

(1) cell의 index 를 이용한 방법

  >> A1 = sheet['A1'] 

  >> A1.value

  Sheet1 A1 value

(2) cell()함수를 이용

  - 파라미터로 row와 column을 사용한다.

  - 마지막 값이 존재하는 셀(row)    : sheet.max_row

  - 마지막 값이 존재하는 셀(column) : sheet.max_column

        Ex)

  >> A1 = sheet.cell(row = 1, column = 1)

  Sheet1 A1 value

(3) 전체 예제 코드

 

import openpyxl

wb = openpyxl.load_workbook('./test.xlsx')
sheet = wb['Sheet1']
print(sheet.cell(row=1, column=1).value)
print("%s" % sheet.max_column)
 

  2) 여러 cell 접근 하기

    (1) 특정 범위

  - cell_range = sheet['A1':'C2']

(2) 특정 row 

  - row10 = sheet[10]

(3) 특정 row 범위 

  - row_range = sheet[5:10]

(4) 특정 Column

  - colC = sheet['C']

(5) 특정 Column 범위

  - col_range = sheet['C:D']

        

Ex) 예제 코드

  - 전체 컬럼과 로우에 접근하느 코드

  

6. OpenPyXL 엑셀파일 생성

 

  1) workbook 생성

    - wb = openpyxl.Workbook() # workbook 함수을 통해 workbook 객체 생성 

                           # 생성시 기본적으로 sheet1이 생성된다. 

  2) sheet 생성

    - sheet2 = wb.create_sheet('sheet2') #마지막에 추가

    - sheet3 = wb.create_sheet('sheet3', 1) #sheet1 자리에 삽입 하여 추가

 

  3) sheet 이름 변경

    - sheet2.title = '업무자동화'

 

  4) workbook 저장   

    - wb.save('저장할 파일이름.xlsx') #워크북에 저장

    - wb.close() #파일 닫기

  

  Ex) 전체 코드 

 

    import openpyxl

 

    wb = openpyxl.Workbook()

    sheet2 = wb.create_sheet('sheet2')

    sheet3 = wb.create_sheet('sheet3', 1)

    sheet2.title = '업무자동화'

    wb.save('./new_test_file.xlsx')

    wb.close()

 

7. OpenPyXL 엑셀파일에 쓰기

 

  1) index를 이용하여 cell에 데이터 쓰기

    - sheet['A1'] = 'hello' #A1에 쓰기

 

  2) cell()함수를 이용하여 데이터 쓰기

    - sheet.cell(row = 1, column = 1, value='wolrd') # A1에 값쓰기

  

  * wb.save('./new_test_file.xlsx')를 사용하여 저장을 해야 완전히 반영된다.

 

8. OpenPyXL에서 지원하는 기능?

 

  - 거의 다 지원함으로 메뉴얼을 보시기 바랍니다. (https://openpyxl.readthedocs.io/en/stable/)

1. Excel 에 데이터 쓰기

        from openpyxl import Workbook

        # 엑셀파일 쓰기
        write_wb = Workbook()

        # 이름이 있는 시트를 생성
        write_ws = write_wb.create_sheet('생성시트')

        # Sheet1에다 입력
        write_ws = write_wb.active
        write_ws['A1'] = '숫자'

        #행 단위로 추가
        write_ws.append([1,2,3])

        #셀 단위로 추가
        write_ws.cell(5, 5, '5행5열')
        write_wb.save("C:/Users/Administrator/Desktop/기준/프로그래밍/과제대행/주식데이터크롤링/숫자.xlsx")

        # 출처 https://myjamong.tistory.com/51

2. Excel 데이터 읽기

        from openpyxl import load_workbook


        # data_only=True로 해줘야 수식이 아닌 값으로 받아온다. 
        load_wb = load_workbook("C:/Users/Administrator/Desktop/기준/프로그래밍/과제대행/주식데이터크롤링/output.xlsx", data_only=True)
        # 시트 이름으로 불러오기 
        load_ws = load_wb['Sheet1']

        # 셀 주소로 값 출력
        print(load_ws['B2'].value)

        # 셀 좌표로 값 출력
        print(load_ws.cell(3, 2).value)


        # 지정한 셀의 값 출력

        get_cells = load_ws['B3' : 'B6']
        for row in get_cells:
            for cell in row:
                print(cell.value)

        # 모든 행 단위로 출력

        for row in load_ws.rows:
            print(row)

        # 모든 열 단위로 출력

        for column in load_ws.columns:
            print(column)

        # 모든 행과 열 출력

        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)

        load_ws.cell(3, 3, 51470)
        load_ws.cell(4, 3, 21470)
        load_ws.cell(5, 3, 1470)
        load_ws.cell(6, 3, 6470)
        load_wb.save("C:/Users/Administrator/Desktop/기준/프로그래밍/과제대행/주식데이터크롤링/output.xlsx")
 
로그인 후 댓글쓰기가 가능합니다.

?

List of Articles
번호 분류 제목 날짜 조회 수
57 AutoHotKey Autohotkey) EditPlus에 구문 색깔 입히기 3 file 2012.08.23 10811
56 AutoHotKey autohotkey) 30분마다 자동으로 디스크 정리하기 file 2013.07.31 33071
55 컴퓨터잡담 Autohotkey 파일 저장시 한글 깨짐 현상 2010.10.11 11175
54 AutoHotKey Autohotkey 브라우저 제어 테스트 file 2015.01.26 8205
53 컴퓨터잡담 autohotkey 변수의 이해 2010.10.02 20656
52 WindowsTip autohotkey regwrite ipv6 제거툴 file 2014.12.27 1540
51 컴퓨터잡담 AutohotKey Postmessage(SendMessage)로 CTRL+C 전송하기 2010.07.11 21420
50 컴퓨터잡담 Autohotkey DllCall() 호출하기 5 2010.12.19 23469
49 AutoHotKey autohotkey command-line 실행시 파라미터 설정 2018.02.14 7250
48 AutoHotKey AutoHotkey COM Standard Library 2 2011.02.10 18046
47 컴퓨터잡담 autohotkey - 변수리스트(Variables and Expressions) 모음 2011.09.30 11830
46 AutoHotKey Autohotkey + mypeople(마이피플) 메시지 전송 1 2013.03.12 15432
45 컴퓨터잡담 Ateros(아테로스) AR9485WB-EG 무선 네트워크 어댑터 드라이버 업데이트 및 다운로드 4 file 2012.11.25 15785
44 Server asp,jsp,php 아이피(ip) 가져오기/확인 file 2013.01.05 11867
43 컴퓨터잡담 arp란? arp 해킹방법 및 차단방법(MAC 다발변조로 인한 인터넷 차단방지) 4 2011.12.26 6681
42 컴퓨터잡담 ARP(mac spoofing) 바이러스 내용 스크랩 3 file 2012.10.19 6438
41 컴퓨터잡담 APMSetup에서 문서 출력 순서 등 설정 2010.07.07 14066
40 Server APMSETUP7 PHP 업그레이드 2015.06.02 6373
39 컴퓨터잡담 API Hooking 유저 레벨 루트킷 1 2010.01.21 11623
38 Server Apache에 대한 mod_proxy 지원 구성 2016.09.06 1801
Board Pagination Prev 1 ... 42 43 44 45 46 Next
/ 46

http://urin79.com

우린친구블로그

sketchbook5, 스케치북5

sketchbook5, 스케치북5

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소