파이썬 - Excel 파일 만들기

  • 이번 포스트에서는 python에서 excel 파일에 대한 기본적인 사용 방법을 알아볼 것이다.

엑셀 관련 모듈

  1. xlwt
  2. openpyxl(추천)
    • 문서화가 제일 잘 되어 있다.
    • 로컬에 엑셀 프로그램이 설치되어 있지 않아도 엑셀 파일 생성 및 읽기 가능
  3. xlsxwriter
  4. pyexcelerate

openpyxl 설치

  • pip install openpyxl

openpyxl sheet 사용법

  • 파일 열기
    • openpyxl.load_workbook(‘파일명’)
    • ex. wb = openpyxl.load_workbook(‘test.xlsx’)
  • 파일 닫기
    • ex. wb.close()
  • sheet 열기
    • ex. wb[‘sheet1’]
  • 현재 열린 sheet 열기
    • ex. ws = wb.active
  • cell 접근 방법
    • cell의 index 이용한 방법
      • a1 = ws[‘A1’]
      • al.value
    • cell() 함수 사용
      • 파라미터로 row, column 사용
      • 마지막 값이 존재하는 셀(row) : sheet.max_row
      • 마지막 값이 존재하는 셀(column): sheet.max_column
      • ex. a1 = sheet.cell(row=1, column=1)

openpyxl 예제

  • ex) score.xlsx

    1
    2
    3
    4
    A  B  C  D  E
    1 80 90 85 합계
    2 88 95 80 합계
    3 90 85 90 합계
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    import openpyxl

    # 엑셀파일 열기
    wb = openpyxl.load_workbook('score.xlsx')

    # 현재 Active Sheet 얻기
    ws = wb.active

    # 국영수 점수 읽기
    for r in ws.rows:
    row_index = r[0].row # 행 인덱스
    kor = r[1].value
    eng = r[2].value
    math = r[3].value
    sum = kor + eng + math

    # 합계 쓰기
    ws.cell(row=row_index, column=5).value = sum

    print(kor, eng, math, sum)

    # 엑셀 파일 저장
    wb.save("score2.xlsx")
    wb.close()
  • score2.xlsx

    1
    2
    3
    4
    A  B  C  D  E
    1 80 90 85 255
    2 88 95 80 263
    3 90 85 90 265

셀의 범위에 접근

  • score.xlsx

    1
    2
    3
    4
    5
        A      B
    1 과목 점수
    2 국어 80
    3 영어 90
    4 수학 95

    단 하나의 셀이 아니라 여러 셀에 접근하는 방법

    1
    2
    3
    4
    multiple_celss = sheet['A1':'B3']
    for row in multiple_cells:
    for cell in row:
    print cell.value

    출력되는 결과

    1
    2
    3
    4
    5
    6
    과목
    점수
    국어
    80
    영어
    90

모든 행과 열에 접근

  • 모든 행에 접근하기 위한 방법

    1
    2
    all_rows = sheet.rows
    print all_rows[:]

    출력되는 결과

    1
    ((<Cell Sheet1.A1>, <Cell Sheet1.B1>), (<Cell Sheet1.A2>, <Cell Sheet1.B2>), (<Cell Sheet1.A3>, <Cell Sheet1.B3>), (<Cell Sheet1.A4>, <Cell Sheet1.B4>))
  • 모든 열에 접근하기 위한 방법

    1
    2
    all_columns = sheet.columns
    print all_columns[:]

    출력되는 결과

    1
    ((<Cell Sheet1.A1>, <Cell Sheet1.A2>, <Cell Sheet1.A3>, <Cell Sheet1.A4>, (<Cell Sheet1.B1>, <Cell Sheet1.B2>, <Cell Sheet1.B3>, <Cell Sheet1.B4>))