개발/python

[python 기초] 엑셀에 구구단 출력하기

xwing 2021. 1. 5. 20:30

Python 과 python 모듈 openpyxl 을 이용해서 엑셀에 구구단을 출력해 봅시다.


openpyxl 설치

site :  openpyxl.readthedocs.io/en/stable/index.html

 

openpyxl - A Python library to read/write Excel 2010 xlsx/xlsm files — openpyxl 3.0.5 documentation

Install openpyxl using pip. It is advisable to do this in a Python virtualenv without system packages: Warning To be able to include images (jpeg, png, bmp,…) into an openpyxl file, you will also need the “pillow” library that can be installed with:

openpyxl.readthedocs.io

설치

pip install openpyxl

openpyxl 이 설치가 안되어 있다면 위를 참고해서 설치한다.

# python 기초
# 엑셀에 구구단 출력하기
#

from openpyxl.styles import Font, Color, Alignment
from openpyxl import Workbook
import openpyxl

def cell_font_style(font_color, font_size, align):
    font = Font(color=font_color, size= font_size )
    alignment = Alignment(horizontal="center", vertical= align)
    return font, alignment
    

wb = Workbook()

for dan in range(2, 10):
    if dan == 2:
        ws = wb.active
        ws.title = str(dan) + "단"
    else:
        ws = wb.create_sheet(str(dan) + "단")

    # title
    style = cell_font_style("FF00FF", 24, "center")
    ws["A1"] =  str(dan) + "단"
    ws.merge_cells("A1:E1")
    A1 = ws["A1"]
    A1.font = style[0]
    A1.alignment = style[1]
    

    for r in range(1, 10):
        multiply =  dan * r
        ws.cell(row= r + 2, column=1, value= dan)
        ws.cell(row= r + 2, column=2, value= "X")
        ws.cell(row= r + 2, column=3).value = r
        ws.cell(row= r + 2, column=4).value = "="
        ws.cell(row= r + 2, column=5, value= multiply)
        ws.row_dimensions[r + 2].height = 35.5

        for c in range(1, 7):
            style = cell_font_style("000000", 14, "center")
            cell = ws.cell(row= r + 2, column = c)
            cell.font = style[0]
            cell.alignment = style[1]
    

wb.save(filename="구구단.xlsx")

Code 는 위와 같습니다.

끝~

 

 

'개발 > python' 카테고리의 다른 글

[python 기초] 엑셀에 달력출력하기  (0) 2021.01.07
파이썬 - pandas LG전자 일봉가져오기  (0) 2020.12.29
yahoo finance 크롤링  (0) 2020.12.19