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

使用Pandas批量处理TXT转Excel时仅生成首个工作表的问题排查

问题分析与解决

你的代码只生成第一个工作表的核心问题有两个:

  1. Excel写入引擎不支持追加模式:pandas默认的xlsxwriter引擎不支持向已有Excel文件追加工作表,必须改用支持追加的openpyxl引擎。
  2. 循环内重复初始化Writer的隐患:每次循环都新建ExcelWriter实例,若文件已存在且引擎不匹配,会导致后续写入失败或覆盖原有内容。

具体修改步骤

1. 安装依赖引擎

首先执行命令安装openpyxl:

pip install openpyxl

2. 修正核心代码

修改ExcelWriter初始化逻辑,指定支持追加的引擎,同时优化路径处理和代码简洁性:

from netmiko import ConnectHandler
from datetime import datetime
import re
from pathlib import Path
import os
import pandas as pd

# 用原始字符串避免路径转义问题
ruta = Path(r"E:\Python\Visual Studio Code Proyects\M2M Real\Archivos")  

def is_free(valor):
    color = 'green' if valor == "free"  else 'white'
    return 'background-color: %s' % color

list_txt = [ruta/"Router_a.txt", ruta/"Router_b.txt"]
# 用Path对象拼接路径,更安全可靠
ruta_host = ruta / "interfaces.xlsx"  

for txt in list_txt:
    host = txt.stem
    sheet_name=f'{host}-Gi0-3-4-2'

    df = pd.read_fwf(txt)
    df["Description"] = (df.iloc[:, 3:].fillna("").astype(str).apply(" ".join, axis=1).str.strip())
    df = df.iloc[:, :4]
    df = df.drop(columns=["Status", "Protocol"])
    df.Interface = df.Interface.str.extract('Gi0/3/4/2\.(\d+)')
    # 简化索引重置逻辑
    df = df[df.Interface.notnull()].reset_index(drop=True)  
    df['Interface'] = df['Interface'].astype(int)
    df = df.set_index('Interface').reindex(range(1,50)).fillna('free').reset_index()
    # 单独存储样式化对象,避免覆盖原始DataFrame
    df_styled = df.style.applymap(is_free)  

    # 根据文件是否存在选择写入模式
    mode = 'a' if ruta_host.exists() else 'w'
    with pd.ExcelWriter(
        ruta_host, 
        mode=mode, 
        engine='openpyxl',
        # 若工作表已存在则覆盖,避免报错
        if_sheet_exists='replace'  
    ) as writer:
        df_styled.to_excel(writer, sheet_name=sheet_name, index=False)

额外优化说明

  • 用Path对象处理路径,避免字符串拼接导致的转义错误。
  • 简化索引重置代码,提升可读性。
  • 单独命名样式化后的对象,保留原始DataFrame便于调试。
  • 添加if_sheet_exists='replace'参数,处理工作表重名的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 22:05:45