我想解析包含几张表的 Excel 文件并将数据保存在 JSON 文件中。
我不想解析第一张和第二张,以及最后一张。我想解析中间的那些,并且工作表的数量并不总是相等,并且这些工作表的名称并不总是相同。
import pandas
import json
# Read excel document
excel_data_df = pandas.read_excel('data.xlsx', sheet_name='sheet1')
有没有办法不放这个参数sheet_name
?
# Convert excel to string
# (define orientation of document in this case from up to down)
thisisjson = excel_data_df.to_json(orient='records')
# Print out the result
print('Excel Sheet to JSON:\n', thisisjson)
# Make the string into a list to be able to input in to a JSON-file
thisisjson_dict = json.loads(thisisjson)
# Define file to write to and 'w' for write option -> json.dump()
# defining the list to write from and file to write to
with open('data.json', 'w') as json_file:
json.dump(thisisjson_dict, json_file)
最佳答案
我只会创建一个工作表级别的字典并循环遍历每个工作表。像这样的事情:
import pandas
import json
sheets = ['sheet1','sheet2','sheet3']
output = dict()
# Read excel document
for sheet in sheets:
excel_data_df = pandas.read_excel('data.xlsx', sheet_name=sheet)
# Convert excel to string
# (define orientation of document in this case from up to down)
thisisjson = excel_data_df.to_json(orient='records')
# Print out the result
print('Excel Sheet to JSON:\n', thisisjson)
# Make the string into a list to be able to input in to a JSON-file
thisisjson_dict = json.loads(thisisjson)
output[sheet] = thisisjson_dict
# Define file to write to and 'w' for write option -> json.dump()
# defining the list to write from and file to write to
with open('data.json', 'w') as json_file:
json.dump(output, json_file)
关于python - 如何使用 pandas 将 Excel 文件转换为 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71832948/