본문 바로가기
Python/PythonLibrary

win32com / xls , xlsx 파일 변환하기

by leehii 2022. 10. 6.
import win32com.client as win32

# 엑셀 Application 
excel = win32com.client.Dispatch("Excel.Application") #엑셀 프로그램 실행

# 새 엑셀 만들기
wb = excel.Workbooks.Add()
ws = wb.Worksheets("sheet1")

# 기존 엑셀 불러오기
wb = excel.Workbooks.Open("경로/파일명.확장자")

# Cell에 데이터 작성
ws.cells(1,1).Value = "text"  # 1,1에 text라는 데이터 작성
ws.Range("A2").Value = "text" # 1,2에 text라는 데이터 작성

#Cell에 다중범위 데이터 작성
ws.Range("A1:C1").Value = "text"
ws.Range(ws.Cells(1,1), ws.Cells(1,3)).Value = "text"

# 파일 저장
wb.Save()
# 다른 이름으로 저장
wb.SaveAs("경로/파일명.확장자")


# 종료
excel.Quit()

 

---파일변환---

 

 

import win32com.client as win32

file = "파일명.xls"
excel = win32.gencache.EnsureDispatch('Excel.Application')
wb = excel.Workbooks.Open(file)
wb.SaveAs(file+"x", FileFormat = 51) # FileFormat = 51 is for .xlsx extension
wb.Close() 
excel.Application.Quit()

 

 

from win32com.client import Dispatch

xl = Dispatch('Excel.Application')
wb = xl.Workbooks.Add('A.xlsx')
wb.SaveAs('A.xlsx'[:-1], FileFormat=56) # FileFormat = 56 is for .xls extension
xl.Quit()