You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python读取CSV并按第二列指定名称生成Excel文件

解决方法

要实现用CSV第二列的名称命名Excel文件,只需要修改两处关键逻辑:

1. 同时读取CSV的查询语句和文件名

原来的代码只提取了CSV第一列的查询内容,现在要把每一行的**查询语句(第一列)和目标文件名(第二列)**一起保存,同时兼容第二列为空的情况:

# 读取CSV中的查询语句和对应文件名,处理UTF-8 BOM
with open(csv_file_path, mode='r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    query_pairs = []
    for row in reader:
        if not row:
            continue
        # 提取第一列的查询语句
        query = row[0]
        # 提取第二列的文件名,为空则用默认命名
        if len(row) >= 2 and row[1].strip():
            file_name = row[1].strip()
        else:
            file_name = f'result_{len(query_pairs)+1}'
        query_pairs.append((query, file_name))

2. 用第二列的名称生成合法的输出文件

循环时直接使用读取到的文件名,同时处理系统禁止的非法字符,避免保存失败:

# 执行查询并保存结果
for idx, (query, file_name) in enumerate(query_pairs, start=1):
    try:
        df = pd.read_sql(query, engine)
       
        # 替换文件名中的非法字符(Windows系统禁止的<>:"/\|?*)
        invalid_chars = '<>:"/\\|?*'
        safe_file_name = ''.join(c if c not in invalid_chars else '_' for c in file_name)
        # 确保文件名以.xlsx结尾
        if not safe_file_name.lower().endswith('.xlsx'):
            safe_file_name += '.xlsx'
        output_file = os.path.join(output_directory, safe_file_name)
       
        df.to_excel(output_file, index=False)
        print(f'已将第{idx}个查询结果保存到 {output_file}')
       
    except Exception as e:
        print(f"执行第{idx}个查询出错: {e}")

完整修改后的代码

import csv
import os
import pandas as pd

# 假设csv_file_path、output_directory、engine已提前定义
# 读取CSV中的查询语句和对应文件名
with open(csv_file_path, mode='r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    query_pairs = []
    for row in reader:
        if not row:
            continue
        query = row[0]
        # 处理第二列空值的情况
        file_name = row[1].strip() if len(row)>=2 and row[1].strip() else f'result_{len(query_pairs)+1}'
        query_pairs.append((query, file_name))

# 执行查询并保存结果到对应命名的Excel文件
for idx, (query, file_name) in enumerate(query_pairs, start=1):
    try:
        df = pd.read_sql(query, engine)
        # 处理非法字符,确保文件名合法
        invalid_chars = '<>:"/\\|?*'
        safe_file_name = ''.join(c if c not in invalid_chars else '_' for c in file_name)
        if not safe_file_name.lower().endswith('.xlsx'):
            safe_file_name += '.xlsx'
        output_file = os.path.join(output_directory, safe_file_name)
        
        df.to_excel(output_file, index=False)
        print(f'已将第{idx}个查询结果保存到 {output_file}')
        
    except Exception as e:
        print(f"执行第{idx}个查询出错: {e}")

关键说明

  • 兼容CSV第二列空值的情况:如果第二列没有内容,自动使用result_N的默认命名
  • 处理文件名中的非法字符,避免因系统限制导致保存失败
  • 强制统一文件后缀为.xlsx,避免出现无后缀或错误后缀的文件

内容的提问来源于stack exchange,提问作者Marcus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 16:07:24