提问人:Mir4 Account 提问时间:8/3/2023 最后编辑:cybernetic.nomadMir4 Account 更新时间:8/3/2023 访问量:27
覆盖 Excel 中的现有工作表
overwriting the existing sheet in excel
问:
它在 Excel 中添加工作表,但在代码完成后,运行 Excel 文件将只有 1 张工作表。请注意,我在 Excel 中有工作表名称模板。
def createNewSheet(currentDate):
wb = openpyxl.load_workbook('employee_data.xlsx')
sheetNames = wb.sheetnames
# Check if the current_date sheet already exists
sheetExists = False
for sheetName in sheetNames:
if sheetName == currentDate:
sheetExists = True
break
if not sheetExists:
# Create a new sheet
newSheet = wb.create_sheet(title=currentDate)
# Read data from the 'Template' sheet using pandas
df_template = pd.read_excel('employee_data.xlsx', sheet_name='Template', engine='openpyxl')
# Get the column headers from the 'Template' sheet
headers = df_template.columns.tolist()
# Write the column headers to the new sheet
for col_num, header in enumerate(headers, start=1):
newSheet.cell(row=1, column=col_num, value=header)
# Copy data starting from row 2 (A2 to last row) to the new sheet
for row_num, row in enumerate(df_template.values, start=2):
for col_num, value in enumerate(row, start=1):
newSheet.cell(row=row_num, column=col_num, value=value)
# Save the new sheet to the workbook
wb.save('employee_data.xlsx')
currentDate = datetime.now().strftime("%Y-%m-%d")
createNewSheet(currentDate)
我希望它添加工作表并用当前日期命名它,然后它将从“模板”工作表中复制数据。
答: 暂无答案
评论