[英]Python: How to add value to a specific excel sheet using openpyxl?
So I wanted to add a value to a specific sheet in this case we have 2 sheets, Student Profile and Student Grades所以我想为特定工作表添加一个值,在这种情况下我们有 2 个工作表,Student Profile 和 Student Grades
from openpyxl import load_workbook
file = load_workbook("Registry.xlsx")
sheet = file.active
sheet.create_sheet("Student Grades")
#Student Profile
sheet["A1"] = "ID No.:"
sheet["B1"] = "Last Name:"
sheet["C1"] = "First Name:"
sheet["D1"] = "Middle Name:"
sheet["E1"] = "Sex:"
sheet["F1"] = "Date of Birth:"
file.save("Registry.xlsx")
but if we do it again with for Student Grades it just overrides the previous values of Student Profile since it stays in the sheet1但是如果我们再次对 Student Grades 执行此操作,它只会覆盖 Student Profile 的先前值,因为它保留在 sheet1 中
file = load_workbook("Registry.xlsx")
sheet = file.active
sheet["A1"] = "ID No:"
sheet["B1"] = "Math"
sheet["C1"] = "Science:"
sheet["D1"] = "English"
file.save("Registry.xlsx")
I tried to do:我试着做:
sheet = file["Student Grades"].active
#or
sheet["Student Grades", "A1"] = "ID No."
but it returns as an error.但它作为错误返回。 But I noticed, if you accessed sheet 2, Student Grades, using Excel and saved before exiting.
但我注意到,如果您使用 Excel 访问表 2,学生成绩并在退出前保存。 It places the value on sheet 2 instead 1. The problem is I need it to be fully automated so I can't access excel beforehand.
它将值放在工作表 2 而不是 1 上。问题是我需要它完全自动化,所以我无法事先访问 excel。
Edit: This is small part of a project with CRUD functions where we're restricted from using databases like sql. So we have to resort to excel instead.编辑:这是一个带有 CRUD 功能的项目的一小部分,我们被限制使用像 sql 这样的数据库。所以我们不得不求助于 excel。 Since it have CRUD functions, excel file needs to be constantly updating when you have a added value to it.
由于它具有 CRUD 功能,所以 excel 文件需要在您对它有附加值时不断更新。 So i have to get that specific sheet and edit the cell values within it
所以我必须得到那个特定的工作表并编辑其中的单元格值
You need to create a sheet for the profiles with Workbook.create_sheet
as you did for the grades.您需要像为成绩所做的那样使用
Workbook.create_sheet
为配置文件创建一个工作表。
Try this:尝试这个:
from openpyxl import load_workbook
wb = load_workbook("Registry.xlsx")
#Student Profile
ws_sp = wb.create_sheet("Student Profiles")
ws_sp["A1"] = "ID No.:"
ws_sp["B1"] = "Last Name:"
ws_sp["C1"] = "First Name:"
ws_sp["D1"] = "Middle Name:"
ws_sp["E1"] = "Sex:"
ws_sp["F1"] = "Date of Birth:"
#Student Grades
ws_sg = wb.create_sheet("Student Grades")
ws_sg["A1"] = "ID No:"
ws_sg["B1"] = "Math"
ws_sg["C1"] = "Science:"
ws_sg["D1"] = "English"
wb.save("Registry.xlsx")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.