Skip to content

Instantly share code, notes, and snippets.

@scottming
Last active December 13, 2023 12:49
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save scottming/99c09685360376d4cac2de7c891e8050 to your computer and use it in GitHub Desktop.
Save scottming/99c09685360376d4cac2de7c891e8050 to your computer and use it in GitHub Desktop.
# -*- coding: utf-8 -*-
import click
import os
import pandas as pd
def file_split(file):
s = file.split('.')
name = '.'.join(s[:-1]) # get directory name
return name
def getsheets(inputfile, fileformat):
name = file_split(inputfile)
try:
os.makedirs(name)
except:
pass
df1 = pd.ExcelFile(inputfile)
for x in df1.sheet_names:
print(x + '.' + fileformat, 'Done!')
df2 = pd.read_excel(inputfile, sheetname=x)
filename = os.path.join(name, x + '.' + fileformat)
if fileformat == 'csv':
df2.to_csv(filename, index=False)
else:
df2.to_excel(filename, index=False)
print('\nAll Done!')
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('inputfile')
@click.option('-f', '--format', type=click.Choice([
'xlsx', 'csv']), default='xlsx', help='Default xlsx.')
def cli(inputfile, format):
'''Convert a Excel file with multiple sheets to several file with one sheet.
Examples:
\b
getsheets filename
\b
getsheets filename -f csv
'''
if format == 'csv':
getsheets(inputfile, 'csv')
else:
getsheets(inputfile, 'xlsx')
cli()
@gaurav
Copy link

gaurav commented Nov 5, 2019

I think it's supposed to be sheet_name rather than sheetname (see https://stackoverflow.com/a/57348202/27310).

@scottming
Copy link
Author

I think it's supposed to be sheet_name rather than sheetname (see https://stackoverflow.com/a/57348202/27310).

Ok, thanks, the code is very old, and pandas is evolving.

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