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

如何用Python解析特殊格式TXT文件并更新Excel表格状态

从特殊格式TXT自动更新Excel状态的实现方案

完全可以实现,以下是基于openpyxl的简单易懂方案,先覆盖核心需求,再预留跨天任务的处理思路:

一、核心步骤说明

1. 解析特殊格式的TXT文件

TXT是带分隔线的表格格式,我们可以通过过滤无效行、分割字段的方式提取所需数据:

  • 跳过以+开头的分隔线行和表头行
  • 用|分割每行内容,去除前后空白后提取Name、end日期、status字段
  • 把end字段的完整时间戳截断为YYYY-MM-DD格式的日期,用于匹配Excel中的日期列

2. 更新Excel表格

假设你的Excel结构为:

  • A列:存储Name(如N1、N2、N3、N4)
  • 第一行:存储日期(如2023-02-08、2023-02-09...)
  • 交叉单元格:对应Name在指定日期的状态(如B2是N1在2023-02-08的状态)

我们先建立Name到行号、日期到列号的映射,再批量更新状态。

二、代码实现

import openpyxl
from datetime import datetime

# ---------------------- 1. 解析TXT文件 ----------------------
txt_path = "your_task_file.txt"
task_data = []

with open(txt_path, "r", encoding="utf-8") as f:
    for line in f:
        line = line.strip()
        # 跳过分隔线、表头和空行
        if not line or line.startswith("+") or line.startswith("| Name"):
            continue
        # 分割并清洗字段
        parts = [p.strip() for p in line.split("|") if p.strip()]
        if len(parts) >= 5:
            name = parts[0]
            # 提取end日期的YYYY-MM-DD部分
            end_datetime = datetime.strptime(parts[3], "%Y-%m-%d %H:%M:%S")
            end_date = end_datetime.strftime("%Y-%m-%d")
            status = parts[4].lower()
            task_data.append({"name": name, "date": end_date, "status": status})

# ---------------------- 2. 更新Excel表格 ----------------------
excel_path = "your_status_table.xlsx"
wb = openpyxl.load_workbook(excel_path)
ws = wb.active  # 操作第一个工作表

# 建立Name到行号的映射(A列)
name_to_row = {}
for row in range(2, ws.max_row + 1):
    name = ws.cell(row=row, column=1).value
    if name:
        name_to_row[name] = row

# 建立日期到列号的映射(第一行)
date_to_col = {}
for col in range(2, ws.max_column + 1):
    cell_value = ws.cell(row=1, column=col).value
    # 兼容Excel日期格式和文本格式的日期
    if isinstance(cell_value, datetime):
        date_str = cell_value.strftime("%Y-%m-%d")
    else:
        date_str = str(cell_value).strip()
    date_to_col[date_str] = col

# 遍历任务数据,更新对应单元格
for task in task_data:
    name = task["name"]
    task_date = task["date"]
    task_status = task["status"].capitalize()  # 统一首字母大写格式
    
    # 定位目标单元格
    row = name_to_row.get(name)
    col = date_to_col.get(task_date)
    if row and col:
        current_status = ws.cell(row=row, column=col).value
        # 按需求更新:仅当当前状态为waiting时替换
        if current_status and current_status.lower() == "waiting":
            ws.cell(row=row, column=col).value = task_status

# 保存修改后的Excel
wb.save(excel_path)
print("Excel状态更新完成")

三、跨天任务的边缘情况预留思路

如果任务存在跨天(start和end不在同一天),可以在解析TXT时扩展逻辑:

  • 计算start到end之间的所有连续日期(包含起止当天)
  • 对每个日期,根据任务状态设置对应单元格(比如跨天的started任务,可将覆盖的所有日期标记为In Progress,具体规则按业务需求调整)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 21:35:16