pip install pywin32
import win32com
python에서 win32com을 제외하고도 openpyxl, xlwings 등이 있지만,
win32com은 MS에서 제공한 기본 API를 wrapping한 형태라 기존 엑셀 기능들을 사용 할 수 있는 장점(?)이 있음
import win32com.client as win32
# 열기
excel = win32.Dispatch('Excel.Application')
excel.Visible = True
# True: excel 창이 켜짐, False: 백그라운드에서 excel이 실행됨
# 닫기
excel.Quit()
import os
import win32com.client as win32
# 엑셀 파일 주소
file_name = '[파일명].xlsx'
xlsx_path = os.getcwd() + rf'\{file_name}'
# => C:\Users\[user_name]\...\[파일명].xlsx
# 열기
file = excel.Workbooks.Open(xlsx_path)
# 저장하기
file.Save()
# 닫기
file.Close(False)
import win32com.client as win32
sheet_name = 'Sheet1'
sheet = file.Worksheets(sheet_name)
def read_data(sheet, y, x):
return sheet.Cells(y, x).Value
def write_data(sheet, y, x, data):
sheet.Cells(y, x).Value = data
sheet_name = 'Sheet1'
sheet = file.Worksheets(sheet_name)
# B1에 Hello 쓰기
write_data(sheet, 1, 2, 'Hello')
# B1의 값 읽기
value = read_data(sheet, 1, 2)
print(value)


A1, B1, C2... 과 같은 인덱싱 방식을 A1-style 이라고 하고
r1c1, r1c2, r2c3... 과 같은 방식을 R1C1-style 이라고 함
def write_formula_a1(sheet, y, x, formula):
sheet.Cells(y, x).Formula = formula
def write_formula_r1c1(sheet, y, x, formula):
sheet.Cells(y, x).FormulaR1C1 = formula
y = 2
x = 1
excel.write_formula_a1(sheet, 1, 3, '=sum(A1:B1)')
excel.write_formula_r1c1(sheet, 2, 3, f'=sum(r{y}c{x}:r{y}c{x+1})')

위에서 번거로웠던 부분을 해결하는 방법
def Address(sheet, pos: tuple, row_absolute=False, column_absolute=False):
if len(pos) == 2:
return sheet.Cells(pos[0], pos[1])\
.GetAddress(RowAbsolute=row_absolute,
ColumnAbsolute=column_absolute)
elif len(pos) == 4:
return sheet.Range(sheet.Cells(pos[0], pos[1]),
sheet.Cells(pos[2], pos[3]))\
.GetAddress(RowAbsolute=row_absolute,
ColumnAbsolute=column_absolute)
else:
return ''
y = 1
x = 1
addr = Address(sheet, (y,x,y,x+1))
print(addr) # A1:B1
addr = Address(sheet, (y,x,y,x+1), True, True)
print(addr) # $A$1:$B$1