python - 如何使用 pandas 将 Excel 文件转换为 json?

标签 python json excel pandas dataframe

我想解析包含几张表的 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/

相关文章:

Python 3.5 导入错误 : dynamic module does not define module export function (PyInit_cv2)

python - pandas statsmodels中的predict(),添加自变量

python - <object> 不是 JSON 可序列化的 django

C++ std::vector 到带有 rapidjson 的 JSON 数组

excel - 在 Access/Excel VBA 中创建字典类型结构?

excel - 使无框用户窗体透明

python - 按组计算 Pandas Dataframe 中列表的重复项计数

python - 创建具有相似拼写的 pandas 数据框变量名称列表

javascript - AngularJS 复选框动态 ng-true-value 表达式

java - Apache POI + JAVA + Excel 在单元格中添加值不起作用