在这个Python程序中,我正在读取一个Excel文件,并根据程序中定义的特定排序顺序对其进行排序。我想用排序后的数据替换原始文件的内容。虽然excel写的是内容,但是数据并没有排序!
我使用 pandas 和 openpyxl 引擎。
经调查,可以看到数据框已排序。当我在控制台中打印相同的内容时,它会给出排序的结果。但是写入后,excel文件并没有体现排序。
这是我的代码:
# Open the output workbook using openpyxl
output_file_path = os.path.join(os.path.dirname(self.template_path), "test.xlsx")
workbook = load_workbook(output_file_path)
# Select the worksheet by name
worksheet = workbook['Sheet1']
# Load the output file into a DataFrame
df = pd.read_excel(output_file_path, engine='openpyxl')
# Load the output file into a DataFrame and sort it
sort_order = ["D1", "D2", "R1", "W"]
print(df.head())
df.sort_values(by=["SortCol"], ascending=True, inplace=True, key=lambda x: pd.Categorical(x, categories=sort_order))
print("Sort Order Result")
print(df)
# Overwrite sorted data in the existing worksheet
for row, record in df.iterrows():
for col, value in record.items():
if row+2 >= 1 and column_mappings[col] >= 1: # added check to ensure row and column values are greater than or equal to 1
worksheet.cell(row=row+2, column=column_mappings[col]+1, value=value)
# Save the changes
workbook.save(output_file_path)
删除以前的文件并再次运行代码,有时以前的文件不会被覆盖。保存到 .csv 文件而不是 .xlsx 也可能有帮助。