본문 바로가기
파이썬

파이썬 데이터 프레임 목록을 다중 시트 Excel 스프레드 시트에 저장

by º기록 2021. 1. 29.
반응형

DataFrame 목록을 하나의 Excel 스프레드 시트로 내보내려면 어떻게해야합니까?


참고
If passing an existing ExcelWriter object, then the sheet will be added to the existing workbook. This can be used to save different 하나의 통합 문서에 대한 DataFrames

작성기 = ExcelWriter ( 'output.xlsx')
df1.to_excel(writer, 'sheet1')
df2.to_excel(writer, 'sheet2')
writer.save ()

그 후 다음과 같이 DataFrame 목록을 하나의 스프레드 시트에 저장하는 함수를 작성할 수 있다고 생각했습니다.

from openpyxl.writer.excel import ExcelWriter
def save_xls(list_dfs, xls_path):
    writer = ExcelWriter(xls_path)
    for n, df in enumerate(list_dfs):
        df.to_excel(writer,'sheet%s' % n)
    writer.save()

그러나 (각각이 to_excel 을 개별적으로 저장할 수있는 두 개의 작은 DataFrame 목록이있는 경우) 예외가 발생합니다 (편집 : 트레이스 백 제거됨) :

AttributeError: 'str' object has no attribute 'worksheets'


 

해결 방법

 

Pandas 고유의 ExcelWriter 클래스를 사용해야합니다.

from pandas import ExcelWriter
# from pandas.io.parsers import ExcelWriter

그러면 save_xls 함수가 예상대로 작동합니다.

def save_xls(list_dfs, xls_path):
    with ExcelWriter(xls_path) as writer:
        for n, df in enumerate(list_dfs):
            df.to_excel(writer,'sheet%s' % n)
        writer.save()

 

참조 페이지 https://stackoverflow.com/questions/14225676

 

 

반응형

댓글