파이썬

엑셀과 파이썬 001

와찬 2023. 7. 19. 17:19

우리가 일을 하다보면 엑셀파일 여러개의 특정시트B를 복사해서

엑셀파일 C에 옮기는 일을 할때가 있습니다.

이경우 파이썬을 활용하여 간단하게 옮길 수가 있습니다.

먼저 파이썬이 있다는 가정하에서 말씀드리겠습니다.

pywin32를 임포트해야하기 땜시

실행에서 cmd 치신후에 pip install pywin32를 깔아줍니다.

아래는 코딩 내역인데, 붉은색만 바까주면 됩니다.

import os

import win32com.client as win32

# List of Excel files to copy sheet from

excel_files = ['국내법인 자금일보 (23.07.12).xlsx', '국내법인 자금일보 (23.07.13).xlsx', '국내법인 자금일보 (23.07.14).xlsx']

# Excel file to copy sheets into

output_file = 'Domestic corporate finance daily summary (A).xlsx'

# Create Excel application object

excel_app = win32.gencache.EnsureDispatch('Excel.Application')

excel_app.Visible = False # Set to True if you want to see Excel in action

# Create a new workbook to copy sheets into

output_workbook = excel_app.Workbooks.Add()

# Iterate over the input Excel files

for file in excel_files:

input_workbook = excel_app.Workbooks.Open(os.path.abspath(file))

input_sheet = input_workbook.Worksheets('B')

output_sheet = output_workbook.Worksheets.Add(After=output_workbook.Sheets(output_workbook.Sheets.Count))

# Copy the data and formatting from the input sheet to the output sheet

input_sheet.UsedRange.Copy()

output_sheet.Range('A1').PasteSpecial()

# Copy merged cell information

merged_ranges = input_sheet.UsedRange.MergeCells

if merged_ranges:

for merged_range in merged_ranges:

output_range = output_sheet.Range(merged_range)

output_range.Merge()

input_workbook.Close()

# Save the output workbook

output_workbook.SaveAs(os.path.abspath(output_file))

output_workbook.Close()

# Quit Excel application

excel_app.Quit()

print("Sheet copied successfully!")

이런거 뜨면 다 예 눌러주고 하면 파일이 취합되어있습니다.

아래 사진처럼요~ 칸 너비라던가 이런건 안되는데

pandas 나 openpyxl에서는 엑셀데이터는 가져오는데 서식이랑 셀병합같은게 안가져와져서 이렇게 해봤습니다~. 칸 넓이 조정하는건 약간만 하면 되니깐...금방 끝내실 수 있을겁니다.

반응형