Ad code

Pandas를 통해서 엑셀 내용을 프로그램적으로 처리하기 용이한 JSON(dict) 구조로 쉽게 변환이 가능하다.

만약 아래와 같은 데이터가 존재한다고 가정하자.


위 문서를 pandas에 존재하는 read_excel을 통해 읽어 드릴 수 있다. 그리고 to_json()을 통해서 진행해보자.

import pandas


excel_df = pandas.read_excel('test.xlsx', sheet_name='Sheet1')

json_str = excel_df.to_json()

print('Excel to JSON:\n', json_str)


이를 가로(열) 기준으로 변경해보자. orient='records' 를 to_json()에 추가하면 열 기준으로 생성하게 된다.


이를 가로(열) 기준으로 변경해보자. orient='records' 를 to_json()에 추가하면 열 기준으로 생성하게 된다.

import pandas


excel_df = pandas.read_excel('test.xlsx', sheet_name='Sheet1')

json_str = excel_df.to_json(orient='records')

print('Excel to JSON:\n', json_str)

우리가 원하던 key, value 스타일로 생성이 된것 같다.


이를 파일로 내보내기를 하고자 한다면, 아래와 같이, open을 통해 파일로 이용하거나, json.loads를 이용해서 dict 구조로 활용할 수 있다.

import pandas


excel_df = pandas.read_excel('test.xlsx', sheet_name='Sheet1')

json_str = excel_df.to_json(orient='records')

with open('test.json', 'w', encoding='utf-8') as f:

    f.write(json_str)


print('Excel to JSON:\n', json_str)


댓글 쓰기

0 댓글