
Файлы Excel генерируются с именем result_1.xlsx, result_2.xlsx. Но теперь я хочу создать файл Excel с именем файла, указанным во втором столбце файла CSV. Например, результат первого запроса следует сохранить как файл с именем test1.xlsx, результат второго запроса следует сохранить с именем файла test2.xlsx. Имя создания файла Excel следует читать из второго столбца файла CSV.

Ниже приведен мой код Python:
# Read queries from the CSV file with UTF-8 encoding to remove BOM
with open(csv_file_path, mode='r', encoding='utf-8-sig') as file:
reader = csv.reader(file)
queries = [row[0] for row in reader if row] # Skip empty rows
# Execute each query and save results to separate Excel files
for i, query in enumerate(queries):
try:
# Execute the query using SQLAlchemy engine
df = pd.read_sql(query, engine)
# Define the output Excel file name
output_file = os.path.join(output_directory, f'result_{i + 1}.xlsx')
# Save the DataFrame to an Excel file
df.to_excel(output_file, index=False)
print(f'Saved results of query {i + 1} to {output_file}')
except Exception as e:
print(f"Error executing query {i + 1}: {e}")
Подробнее здесь: https://stackoverflow.com/questions/791 ... ame-python
Мобильная версия