Advertisement
AyanUpadhaya

Working with json file and openpyxl

May 26th, 2021
158
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.25 KB | None | 0 0
  1. #Working with json file and openpyxl
  2. #The custom program scrapes data from a custom json file and saves in a excel file
  3. #script written by Ayan Upadhaya, contact: ayanu881@gmail.com
  4.  
  5. import json
  6. import openpyxl
  7. from openpyxl.styles import Font
  8.  
  9. #importing data from json file
  10. with open('persons.json','r') as f:
  11.     data=json.load(f)
  12.  
  13. #creating a blank workbook
  14. wb=openpyxl.Workbook()
  15. sheet=wb.active
  16.  
  17. #columns and their headings and font style
  18. columns=['A','B','C','D']
  19. headings=['name','age','job','city']
  20. fontObj=Font(name="Arial",bold=True)
  21.  
  22. #setting up column dimension
  23. for cols in columns:
  24.     sheet.column_dimensions[cols].width=15
  25.  
  26. #seting up titles for columns
  27. index=1
  28. for i in range(len(columns)):
  29.     sheet[columns[i]+str(index)]=headings[i].capitalize()
  30.     sheet[columns[i]+str(index)].font=fontObj
  31.  
  32. #exporting all data to excel file sheet
  33. trac=2
  34. for i in data['persons']:
  35.     index=0
  36.     sheet[columns[index]+str(trac)]=i['name'].capitalize()
  37.     sheet[columns[index+1]+str(trac)]=i['age']
  38.     sheet[columns[index+2]+str(trac)]=i['job'].capitalize()
  39.     sheet[columns[index+3]+str(trac)]=i['city'].capitalize()
  40.     trac+=1
  41.  
  42.  
  43. wb.save('scrape.xlsx')
  44.  
  45. print("Success")
  46.  
  47. #how to read json data in terminal
  48. #for i in data['persons']:
  49. #   print(f"{i['name']}\t{i['age']}\t{i['job']}\t\t{i['city']}")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement