当我尝试将 pandas 数据框保存到现有的 Excel 工作表时,它可以工作。
workbook = load_workbook('excel_file.xlsx')
def prepare_to_validate_sheet():
to_validate_sheet = workbook['To Validate']
dataframe = pd.read_csv('to_validate.csv', sep = ';')
writer = pd.ExcelWriter('excel_file.xlsx', engine = 'openpyxl', mode = "a", if_sheet_exists = "replace")
writer.worksheets = dict((ws.title, ws) for ws in workbook.worksheets)
dataframe.to_excel(writer, sheet_name = 'To Validate', index = False)
writer.close()
但是当我尝试使用下一个功能更改另一张纸
Installation
时,前一张To Validate
变为空。同时更改将保存在Installation
工作表上。
def prepare_installation_sheet():
installation_sheet = workbook['Installation']
installation_sheet.cell(row = 1, column = 1).value = installation_title
installation_sheet.cell(row = 4, column = 1).value = installation_text
workbook.save('excel_file.xlsx')
我该如何解决它?
这样,原始“要验证”工作表及其数据将保留在original_workbook中,而对“安装”工作表的更改将保存在具有不同名称的新工作簿中。
from openpyxl import load_workbook, Workbook
# Load the original workbook
original_workbook = load_workbook('excel_file.xlsx')
installation_sheet = original_workbook['Installation']
installation_sheet.cell(row=1, column=1).value = installation_title
installation_sheet.cell(row=4, column=1).value = installation_text
new_workbook = Workbook()
for sheet_name in original_workbook.sheetnames:
original_sheet = original_workbook[sheet_name]
new_sheet = new_workbook.create_sheet(title=sheet_name)
for row in original_sheet.iter_rows(values_only=True):
new_sheet.append(row)
# Save the new workbook with a different name or path
new_workbook.save('new_excel_file.xlsx')