[英]How can I write json data in an existing excel by overwriting in a sheet using pandas?
I have some sample json data in the below format:我有一些样本 json 数据,格式如下:
{"VM": {"0": "v1", "1": "v2", "2": "v3", "3": "v4"},
"Size in TB": {"0": "112", "1": "100", "2": "123", "3": "109"},
"state": {"0": "ON", "1": "OFF", "2": "OFF", "3": "ON"}}
I want to store this data in an existing excel file by overwriting an existing sheet.我想通过覆盖现有工作表将此数据存储在现有 excel 文件中。 I am aware of the long approach where I'll convert this json data to an excel sheet then I can copy the new excel to the existing sheet.我知道我将把这个 json 数据转换为 excel 工作表的长期方法,然后我可以将新的 excel 复制到现有工作表。
import pandas as pd
json_data = pd.read_json(r'C:\Users\XYZ\data.json')
datafrme = pd.DataFrame(json_data)
datafrme.to_excel('C:/Users/XYZ/OutputExcelFileWithoutIndex.xlsx',index=False)
Now this new excel file can be pasted into the existing one.现在这个新的 excel 文件可以粘贴到现有的文件中。
from openpyxl import load_workbook
wb = load_workbook(r'C:\Users\XYZ\OutputExcelFileWithoutIndex.xlsx',data_only=True)
wb2 =load_workbook(r'C:\Users\XYZ\output.xlsx')
sheet1=wb["Sheet1"]
sheet2=wb2["Sheet5"]
for i in range(1,sheet1.max_row+1):
for j in range(1,sheet1.max_column+1):
sheet2.cell(row=i,column=j).value=sheet1.cell(row=i,column=j).value
do we have any direct approach of directly copying json data in an existing excel?我们有什么直接的方法可以直接复制现有 excel 中的 json 数据吗?
To write the df
directly to a sheet in an existing Excel file, you could write the following:要将df
直接写入现有 Excel 文件中的工作表,您可以编写以下内容:
df_json = pd.read_json(r'C:\Users\XYZ\data.json')
# `mode='a' stands for "append', `if_sheet_exists='replace'` overwrites entire sheet,
# if sheet does not yet exist, it will be created
with pd.ExcelWriter(r'C:\Users\XYZ\output.xlsx', mode='a',
if_sheet_exists='replace', engine='openpyxl') as writer:
df_json.to_excel(writer, sheet_name='Sheet1', index=None)
Result:结果:
If you dislike the standard (index, and) header formatting, shift df.columns
to the first row of your df
, and add header=None
.如果您不喜欢标准(索引和) header 格式, df.columns
移至df
的第一行,并添加header=None
。 Like so:像这样:
with pd.ExcelWriter(r'C:\Users\XYZ\output.xlsx', mode='a',
if_sheet_exists='replace', engine='openpyxl') as writer:
df_json.T.reset_index().T.to_excel(writer, sheet_name='Sheet2',
index=None, header=None)
Result:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.