current position:Home>Python Web Development of Student Management System (6) Excel File Import

Python Web Development of Student Management System (6) Excel File Import

2022-09-09 03:16:47weixin_38107457

pip install openpyxl

Tested in test.py

import openpyxldef read_excel_dict(path:str):"""Read Excel data and store as dictionary --- [{},{},{},]"""# Instantiate a wrokbookworkbook = openpyxl.load_workbook(path)# Instantiate a sheetsheet = workbook['student']# Define a variable to store the final data --[]students = []# prepare keykeys = ['sno','name','gender','birthday','mobile','email','address']# traversefor row in sheet.rows:# define a temporary dictionarytemp_dict = {}# Combine value and keyfor index,cell in enumerate(row):# group andtemp_dict[keys[index]] = cell.value# append to liststudents.append(temp_dict)#returnreturn studentsdef write_to_excel(data:list, path:str):"""Write database to Excel"""# Instantiate a workbookworkbook = openpyxl.Workbook()# activate a sheetsheet = workbook.active# Name the sheetsheet.title = 'student'# prepare keyskeys = data[0].keys()# Prepare to write datafor index in range(0, len(data)):# loop through each elementfor cell in range(0, len(data[index])):sheet.cell(row=index + 1, column=cell + 1, value=str(data[index][keys[cell]]))# write to fileworkbook.save(path)if __name__ == '__main__':path="D:\student01.xlsx"# Call functions!students = read_excel_dict(path)# outputprint(students)

KeyError: ‘Worksheet sheet does not exist.’

Change to the same name as the sheet in excel.

copyright notice
author[weixin_38107457],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/252/202209090310251991.html

Random recommended