Skip to content

Instantly share code, notes, and snippets.

@paulmelnikow
Last active June 1, 2022 07:25
Show Gist options
  • Save paulmelnikow/df55015acfcc4df101e9b568c408e97a to your computer and use it in GitHub Desktop.
Save paulmelnikow/df55015acfcc4df101e9b568c408e97a to your computer and use it in GitHub Desktop.
Convert Excel to JSON using pandas
#!/usr/bin/env python3
'''
MIT License
Copyright (c) 2018 Paul Melnikow
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
'''
def parse_args():
import argparse
import os
parser = argparse.ArgumentParser(description='Convert Excel to JSON')
parser.add_argument(
'-f', '--force',
help='Overwrite destination file if it already exists')
parser.add_argument(
'-o', '--outfile',
help='Destination file (.json)')
parser.add_argument(
'-q', '--quiet',
action='store_true',
default=False,
help='Be quiet')
parser.add_argument(
'src',
nargs='+',
type=str,
help='source file (.xlsx)')
return parser.parse_args()
def records_for_json(df):
columns = [str(k) for k in df.columns]
return [dict(zip(columns, row)) for row in df.values]
def main():
import os
import simplejson as json
import pandas as pd
class PandasJsonEncoder(json.JSONEncoder):
def default(self, obj):
import datetime
if any(isinstance(obj, cls) for cls in (datetime.time, datetime.datetime, pd.Timestamp)):
return obj.isoformat()
elif pd.isnull(obj):
return None
else:
return super(PandasJsonEncoder, self).default(obj)
args = parse_args()
for src in args.src:
if args.outfile:
dst = args.outfile
else:
filename, _ = os.path.splitext(os.path.basename(src))
dst = f'{filename}.json'
all_sheet_data = []
for sheet_name in pd.ExcelFile(src).sheet_names:
sheet = pd.read_excel(src, sheet_name=sheet_name)
records = records_for_json(sheet)
all_sheet_data.append({ 'sheet_name': sheet_name, 'records': records })
mode = 'w' if args.force else 'x'
with open(dst, mode) as f:
json.dump(all_sheet_data, f, ignore_nan=True, cls=PandasJsonEncoder, indent=4)
if not args.quiet:
arrow = '\u2192'
print(f'{src} {arrow} {dst}')
if __name__ == '__main__':
main()
@sawaYch
Copy link

sawaYch commented Jun 1, 2022

install deps:

pip3 install openpyxl datetime pandas simplejson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment