I would like to parse Excel file which has a couple of sheets and save a data in JSON file.
I don’t want to parse first and second sheet, and also the last one. I want to parse those in between and that number of sheets is not always equal and names of those sheets are not always the same.
JavaScript
x
6
1
import pandas
2
import json
3
4
# Read excel document
5
excel_data_df = pandas.read_excel('data.xlsx', sheet_name='sheet1')
6
Is there a way not to put this parameter sheet_name
?
JavaScript
1
15
15
1
# Convert excel to string
2
# (define orientation of document in this case from up to down)
3
thisisjson = excel_data_df.to_json(orient='records')
4
5
# Print out the result
6
print('Excel Sheet to JSON:n', thisisjson)
7
8
# Make the string into a list to be able to input in to a JSON-file
9
thisisjson_dict = json.loads(thisisjson)
10
11
# Define file to write to and 'w' for write option -> json.dump()
12
# defining the list to write from and file to write to
13
with open('data.json', 'w') as json_file:
14
json.dump(thisisjson_dict, json_file)
15
Advertisement
Answer
I would just create a sheet level dict and loop through each of the sheets. Something like this:
JavaScript
1
24
24
1
import pandas
2
import json
3
4
sheets = ['sheet1','sheet2','sheet3']
5
output = dict()
6
# Read excel document
7
for sheet in sheets:
8
excel_data_df = pandas.read_excel('data.xlsx', sheet_name=sheet)
9
10
# Convert excel to string
11
# (define orientation of document in this case from up to down)
12
thisisjson = excel_data_df.to_json(orient='records')
13
14
# Print out the result
15
print('Excel Sheet to JSON:n', thisisjson)
16
17
# Make the string into a list to be able to input in to a JSON-file
18
thisisjson_dict = json.loads(thisisjson)
19
output[sheet] = thisisjson_dict
20
# Define file to write to and 'w' for write option -> json.dump()
21
# defining the list to write from and file to write to
22
with open('data.json', 'w') as json_file:
23
json.dump(output, json_file)
24