Код: Выделить всё
for filename_out in os.listdir(output_directory):
if filename_out.endswith(".xlsx"):
file_path_out = os.path.join(output_directory, filename_out)
wb = load_workbook(file_path_out)
summary_sheet = wb['VCC_Summary']
# Write basic info to specified cells
summary_sheet['G4'] = proj_name
summary_sheet['G5'] = proj_no
for period_name, period in time_periods.items():
for key, fin_data in fin_data_dict.items():
period, dir_num = key
# Check if the current key has not been processed
if key not in processed_keys:
target_sheet = get_target_sheet(dir_num)
# Check if a target file is determined
if target_sheet and period == period_name:
try:
ws = wb[target_sheet]
# Determine rows and columns to populate
start_row = rows_to_pop(period_name)
start_col = cols_to_pop(dir_num)
# Call the function to populate the worksheet
pop_sheet(ws, fin_data, start_row, start_col, period_name, dir_num)
processed_keys.add(key)
except PermissionError as err:
print(f">>>>>>>Permission error occurred for file '{file_path_out}': {err}")
break
except Exception as err:
print(f">>>>>>>>An unexpected error occurred: {err}")
continue
wb.save(file_path_out)
wb.close()
Код: Выделить всё
def pop_sheet(ws, fin_data, start_row, start_col, period_name, dir_num):
col_letter = get_column_letter(start_col)
# Print information about the cell being populated
print(f"Populating column {col_letter} in worksheet {ws.title} at {start_row} with {fin_data.head(2)}"
f"for period_name: {period_name}, movement/approach: {dir_num}")
# Specify the starting cell for the DataFrame
start_cell = f"{col_letter}{start_row}"
# Write the DataFrame to the Excel file starting from the specified cell
with pd.ExcelWriter(file_path_out, mode='a', engine = 'openpyxl', if_sheet_exists='overlay') as writer:
fin_data.to_excel(writer, sheet_name=ws.title, startrow=start_row-1, startcol=start_col-1, header=False, index=False)
Заполнение столбца AI на листе Eastbound_VCC в 109 с помощью
M.Cycle Auto 0 0 Автобус 0 0 0 0 Грузовик 0 0 Время езды на велосипеде
19:00 0 57 NaN NaN 0 NaN NaN NaN NaN 1 NaN NaN 7
19:15 2 44 NaN NaN 1 NaN NaN NaN NaN 2 NaN NaN 9
для периода_имя: Ночь, движение/подход: 2
но не удается выполнить запись на мои листы в книге Excel. Я подозреваю, что это может быть связано с тем, как я пишу pd.ExcelWriter или .to_excel, или это может быть логическая ошибка в моем основном цикле. Без кода, вызывающего какие-либо ошибки, я ничего не могу подтвердить. Как мне к этому подойти?
Подробнее здесь: https://stackoverflow.com/questions/781 ... excel-file