JSON格式成績資訊寫入excel

2022-09-17 14:57:14 字數 2033 閱讀 5213

實現如下,其中,造資料函式就是為了造json格式檔案寫的

import

xlwt

import

json

data_score=

#造資料,把資料來源作為json格式存入檔案

defcreate_data(name,data_text):

file=open_file(name,'w'

) json.dump(data_text, file, ensure_ascii=false, indent=4) #

自迴圈json格式寫入檔案

close_file(file)

#開啟檔案

def open_file(filename,mode='r'

): result=open(filename,mode,encoding='

utf-8')

return result #

返回檔案物件

#關閉檔案

defclose_file(file):

file.close()

#把表頭寫入excel檔案

defwrite_table_head(sheet):

sheet.write(0,0,"學號

") #

第乙個引數是行,第二個引數是列,第三個引數是該單元格的內容

sheet.write(0,1,"姓名"

) sheet.write(0,2,"數學"

) sheet.write(0,3,"語文"

) sheet.write(0,4,"英語"

) sheet.write(0,5,"總分"

) sheet.write(0,6,"

平均分")#

寫表內容

defwrite_table(sheet,data_list):

row=1 #

從第1行開始寫

for key,value in data_list.items(): #

遍歷多重字典的第一層

col =0

sheet.write(row,col,key)

col+=1 #

列加for value2 in value: #

遍歷字典第二層的list

sheet.write(row,col,value2)

col+=1 #

列加 count=sum(value[1:]) #

切片方式取3門成績進行求和

sheet.write(row,col,count)#

寫入總分

sheet.write(row,col+1,'

%.2f

' %(count/3)) #

寫入平均值

row+=1 #行加#

讀取檔案的json格式轉換為dic格式

defjson_dic(name):

context =open_file(name)

data_list =json.load(context)

close_file(context)

return

data_list

name='

c.txt

'create_data(name,data_score)

#造資料

book=xlwt.workbook() #

例項化乙個物件

sheet = book.add_sheet("

成績") #

為excle加sheet且命名

write_table_head(sheet) #

寫表頭write_table(sheet,json_dic(name)) #

寫表內容

book.s**e("

score2.xls

") #

儲存檔案

Object寫入json檔案

由於現階段呼叫第三方介面需要以json檔案的格式傳遞json串,類似下圖這種 以前是http直接傳遞json串,現在需要轉化一下,此方法適用於所有型別的資料轉成json檔案,只需要將需要的資料轉化成json格式,然後呼叫這個方法即可 public static boolean createjsonf...

python 將json資料格式化寫入檔案

from taxii2client import server import json server server api roots server.api roots for api root in api roots collections api root.collections for co...

json 格式轉換

datarow 轉換成json格式 public static string tojson datarow drrights jsonbuilder.remove jsonbuilder.length 1,1 jsonbuilder.remove jsonbuilder.length 1,1 ret...