본문 바로가기

Python

엑셀 워크북의 웍크시트 데이터 병합

1. 하나의 엑셀 파일에(워크북)에 여러가지 시트에 데이터가 존재할 경우 병합하는 방법

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import openpyxl
import pandas as pd
import sys
from openpyxl import load_workbook  
location = os.getcwd()
sys.path.append("C:\\pytest")
xlsxFile = 'C:\\pytest\\commoditydata.xlsx'
sheetList = []
 
# openpyxl를 이용하여 시트명 가져오기
wb = openpyxl.load_workbook(xlsxFile)
for i in wb.sheetnames:
    sheetList.append(i)
 
# 데이터프레임 병합
if len(sheetList) != 0:
    df1 = pd.read_excel(xlsxFile, sheetList[0], index_col = 'DATE', parse_dates = True)
    for item in sheetList[1:]:
        df2 = pd.read_excel(xlsxFile, item, index_col = 'DATE', parse_dates = True)
        df_total = pd.concat([df1, df2], axis = 1)
        df1 = df_total
 
df_total.to_excel('C:\\pytest\\looptotal.xlsx', index = True, sheet_name = 'total')
 
 

2. 막상 찾으면 쓸모있는 코드는 별로 없다. 위 코드가 좋은 건지는 잘 모르겠음.