# PG万般：Coze`万人使用`Excel分析器免费开源

> PG万般开源的Coze Excel分析器，支持上传Excel自动识别维度、生成分析代码、输出Markdown表格与Echarts图表，最终转为PDF下载。有效解决大模型处理大数据时的幻觉问题，已有万人使用。

- 来源: https://www.waytoagi.com/kb/ai-agents/coze-excel-analyzer
- 飞书原文: https://waytoagi.feishu.cn/wiki/QMYzwoqSbigx4DkshUQcSjxwnIh
- 更新于: 2026-12-02

---

> 作者：pg万般

---

# 一，基本信息

- 直达链接

- 效果图

![](https://www.waytoagi.com/api/kb-media/Oh7sbz8pWonEL9xgBGccwefSnch)

- 应用使用数据

![](https://www.waytoagi.com/api/kb-media/AMqRbaDxPo3fcLxbcPycQoSjndd)

---

# 二，需求分析

- 来源：电商公司需要做一条工作流，对数据进行清洗与可视化设计。

- 需求痛点：主要是数据量特别大，如果直接传给通用大模型会有幻觉

# 三，业务流程设计

![飞书画板](https://www.waytoagi.com/api/kb-media/board/LtHEwZwkjhsP9BbhC3YcyiNJnGd)

# 四，数据分析自动化系统需求说明

## 业务流程概述

### 整体流程

### 核心功能需求

1. 用户上传Excel文件进行数据分析

2. 系统自动识别数据维度并生成分析配置代码

3. 根据配置代码生成全量数据分析结果

4. 输出Markdown格式的表格和Echarts图表

5. 将Markdown格式转PDF保存到本地下载

### 二创方向

接入自己数据库 或者形成月报日报接入自己飞书

## Coze工作流

![](https://www.waytoagi.com/api/kb-media/I0fkbcPyAomfJjxhr9BczQfzngh)

> 🎬 此处为飞书附件「ai_data - 工作流 -智能体平台.pdf」，[在飞书知识库查看](https://waytoagi.feishu.cn/wiki/QMYzwoqSbigx4DkshUQcSjxwnIh)

# 五，插件代码

## Markdown转PDF(存七牛)代码

**输入参数示例图：**

按照这个命名规范即可复制所有代码

![](https://www.waytoagi.com/api/kb-media/TKFJbLh20o5Ttux3XgfcJUNunbF)

插件入参操作指引文档：[Markdown转PDF_存七牛，入参说明](https://rwlk8bzvsp1.feishu.cn/docx/ED9wd6mKsokOioxwoP9cVyKznRd?from=from_copylink)

- 复制需要把 我提供的代码中 前两行代码删掉，不要删掉 自己 新建插件的前两行，那是插件文件唯一指向

![](https://www.waytoagi.com/api/kb-media/E9KnbJ4yOoPcErxyNUAceR3Qnnb)

```python
from runtime import Args
from typings.markdown_pdf.markdown_pdf import Input, Output
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.lib import colors
from reportlab.lib.utils import ImageReader
import requests
from io import BytesIO
import re
import random
import string
import os
from qiniu import Auth, put_file, etag
from datetime import datetime

class MarkdownToPDF:
    def __init__(self, output_path):
        self.c = canvas.Canvas(output_path, pagesize=A4)
        self.width, self.height = A4
        self.y = self.height - 50
        self.left_margin = 40
        self.line_height = 20
        pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light'))
        self.styles = {
            'normal': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.black
            },
            'title': {
                'font': 'STSong-Light',
                'size': 16,
                'color': colors.black
            },
            'strong': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.blue,
                'bold': True
            },
            'em': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.black,
                'italic': True
            },
            'mark': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.black,
                'background': colors.yellow
            },
            'del': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.gray,
                'strike': True
            },
            'code': {
                'font': 'Courier',
                'size': 11,
                'color': colors.black,
                'background': colors.lightgrey
            },
            'u': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.black,
                'underline': True
            },
            'big': {
                'font': 'STSong-Light',
                'size': 14,
                'color': colors.black
            },
            'small': {
                'font': 'STSong-Light',
                'size': 10,
                'color': colors.black
            },
            'red': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.red
            },
            'orange': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.orange
            },
            'blue': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.blue
            },
            'green': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.green
            },
            'purple': {
                'font': 'STSong-Light',
                'size': 12,
                'color': colors.purple
            }
        }

    def download_image(self, url):
        try:
            response = requests.get(url)
            if response.status_code == 200:
                return ImageReader(BytesIO(response.content))
        except Exception as e:
            print(f"下载图片失败: {e}")
        return None

    def draw_image(self, url):
        img = self.download_image(url)
        if img:
            img_width = self.width - 2 * self.left_margin
            img_height = img_width * 0.5
            if self.y - img_height < 50:
                self.c.showPage()
                self.y = self.height - 50
            self.c.drawImage(img, self.left_margin, self.y - img_height, width=img_width, height=img_height)
            self.y -= (img_height + 20)

    def _process_color(self, color, text):
        """处理颜色标签"""
        color = color.strip().lower()
        return f'<color:{color}>{text}</color:{color}>'

    def clean_text(self, text):
        # 处理Markdown原生语法
        text = re.sub(r'\*\*(.*?)\*\*', r'<strong>\1</strong>', text)
        text = re.sub(r'\*(.*?)\*', r'<em>\1</em>', text)
        text = re.sub(r'~~(.*?)~~', r'<del>\1</del>', text)
        text = re.sub(r'`(.*?)`', r'<code>\1</code>', text)
        text = re.sub(r'==(.*?)==', r'<mark>\1</mark>', text)

        # 处理HTML样式标签
        text = re.sub(r'<span style="font-weight:\s*bold[^"]*">(.*?)</span>', r'<strong>\1</strong>', text)
        text = re.sub(r'<span style="font-weight:\s*[5-9]00[^"]*">(.*?)</span>', r'<strong>\1</strong>', text)
        text = re.sub(r'<span style="font-style:\s*italic[^"]*">(.*?)</span>', r'<em>\1</em>', text)
        text = re.sub(r'<span style="text-decoration:\s*underline[^"]*">(.*?)</span>', r'<u>\1</u>', text)
        text = re.sub(r'<span style="text-decoration:\s*line-through[^"]*">(.*?)</span>', r'<del>\1</del>', text)

        # 处理字体大小
        text = re.sub(r'<span style="font-size:\s*large[^"]*">(.*?)</span>', r'<big>\1</big>', text)
        text = re.sub(r'<span style="font-size:\s*small[^"]*">(.*?)</span>', r'<small>\1</small>', text)
        text = re.sub(r'<span style="font-size:\s*([0-9]+)px[^"]*">(.*?)</span>', r'<span size="\1">\2</span>', text)

        # 处理颜色
        text = re.sub(r'<font color="([^"]+)">(.*?)</font>', lambda m: self._process_color(m.group(1), m.group(2)), text)
        text = re.sub(r'<font color=([^>\s]+)>(.*?)</font>', lambda m: self._process_color(m.group(1), m.group(2)), text)

        # 处理其他HTML标签
        text = re.sub(r'<b>(.*?)</b>', r'<strong>\1</strong>', text)
        text = re.sub(r'<i>(.*?)</i>', r'<em>\1</em>', text)
        text = re.sub(r'<s>(.*?)</s>', r'<del>\1</del>', text)
        text = re.sub(r'<u>(.*?)</u>', r'<u>\1</u>', text)

        # 标准化标签
        tags = ['strong', 'em', 'del', 'code', 'mark', 'u', 'big', 'small', 'font', 'center', 'right']
        for tag in tags:
            text = re.sub(f'<\s*/\s*{tag}\s*>', f'</{tag}>', text)
            text = re.sub(f'<\s*{tag}\s*>', f'<{tag}>', text)

        # 处理URL前的空格
        text = re.sub(r'\s+(?=https?://)', '', text)

        # 处理时间戳
        def format_date(match):
            try:
                timestamp = int(match.group(0))
                return datetime.fromtimestamp(timestamp).strftime('%Y/%m/%d %H:%M:%S')
            except:
                return match.group(0)

        text = re.sub(r'\b\d{10}\b', format_date, text)

        return text

    def draw_text_with_style(self, text, style='normal', x=None):
        if not text:
            return 0
        if x is None:
            x = self.left_margin
            
        # 获取样式配置
        style_config = self.styles.get(style, self.styles['normal'])
        
        # 设置字体和颜色
        self.c.setFont(style_config['font'], style_config['size'])
        self.c.setFillColor(style_config['color'])
        
        if 'background' in style_config:
            text_width = self.c.stringWidth(text, style_config['font'], style_config['size'])
            self.c.setFillColor(style_config['background'])
            self.c.rect(x, self.y - 2, text_width, self.line_height - 2, fill=True)
            self.c.setFillColor(style_config['color'])
            
        self.c.drawString(x, self.y, text)
        return self.c.stringWidth(text, style_config['font'], style_config['size'])

    def draw_paragraph(self, text, is_list_item=False):
        if not text:
            return
        text = self.clean_text(text)
        
        x = self.left_margin
        if is_list_item:
            self.c.drawString(x, self.y, "•")
            x += 20
        
        current_x = x
        segments = []
        current_pos = 0
        
        patterns = [
            (r'<strong>(.*?)</strong>', 'strong'),
            (r'<em>(.*?)</em>', 'em'),
            (r'<del>(.*?)</del>', 'del'),
            (r'<code>(.*?)</code>', 'code'),
            (r'<mark>(.*?)</mark>', 'mark'),
            (r'<u>(.*?)</u>', 'u'),
            (r'<big>(.*?)</big>', 'big'),
            (r'<small>(.*?)</small>', 'small'),
            (r'<color:red>(.*?)</color:red>', 'red'),
            (r'<color:orange>(.*?)</color:orange>', 'orange'),
            (r'<color:blue>(.*?)</color:blue>', 'blue'),
            (r'<color:green>(.*?)</color:green>', 'green'),
            (r'<color:purple>(.*?)</color:purple>', 'purple')
        ]
        
        while current_pos < len(text):
            earliest_match = None
            earliest_style = None
            earliest_pos = float('inf')
            for pattern, style in patterns:
                match = re.search(pattern, text[current_pos:])
                if match and match.start() + current_pos < earliest_pos:
                    earliest_match = match
                    earliest_style = style
                    earliest_pos = match.start() + current_pos
            if earliest_match is None:
                if current_pos < len(text):
                    segments.append(('normal', text[current_pos:]))
                break
            if earliest_pos > current_pos:
                segments.append(('normal', text[current_pos:earliest_pos]))
            segments.append((earliest_style, earliest_match.group(1)))
            current_pos = earliest_pos + len(earliest_match.group(0))

        for style, content in segments:
            words = list(content)
            for word in words:
                word_width = self.c.stringWidth(word, self.styles[style]['font'], self.styles[style]['size'])
                
                if current_x + word_width > self.width - self.left_margin:
                    self.y -= self.line_height
                    current_x = x
                    
                    if self.y < 50:
                        self.c.showPage()
                        self.y = self.height - 50
                        self.c.setFont(self.styles[style]['font'], self.styles[style]['size'])
                        self.c.setFillColor(self.styles[style]['color'])
                
                width = self.draw_text_with_style(word, style, current_x)
                current_x += width

        self.y -= self.line_height * 1.5
        
        if self.y < 50:
            self.c.showPage()
            self.y = self.height - 50

    def process_markdown(self, markdown_text):
        def format_datetime(match):
            try:
                date_str = match.group(0)
                if re.match(r'\d{4}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}', date_str):
                    return date_str
                formats = [
                    '%Y/%m/%d %H:%M:%S',
                    '%Y-%m-%d %H:%M:%S',
                    '%Y%m%d%H%M%S'
                ]
                for fmt in formats:
                    try:
                        dt = datetime.strptime(date_str, fmt)
                        return dt.strftime('%Y/%m/%d %H:%M:%S')
                    except:
                        continue
                return date_str
            except:
                return date_str

        markdown_text = re.sub(r'\d{4}[-/]\d{2}[-/]\d{2}\s+\d{2}:\d{2}:\d{2}', format_datetime, markdown_text)

        lines = markdown_text.split('\n')
        for line in lines:
            line = line.strip()
            if not line:
                self.y -= self.line_height
                continue
            if line.startswith('# '):
                self.y -= 10
                self.draw_text_with_style(line[2:], 'title')
                self.y -= 20
                continue
            if '![' in line and '](' in line:
                match = re.search(r'!\[.*?\]\((.*?)\)', line)
                if match:
                    self.draw_image(match.group(1))
                continue
            if line.startswith('----'):
                self.y -= 10
                self.c.line(self.left_margin, self.y, self.width - self.left_margin, self.y)
                self.y -= 20
                continue
            if line.startswith('- '):
                self.draw_paragraph(line[2:], True)
                continue
            self.draw_paragraph(line)

    def save(self):
        self.c.save()

def generate_random_filename():
    letters = ''.join(random.choices(string.ascii_letters, k=6))
    numbers = ''.join(random.choices(string.digits, k=6))
    return f"{letters}{numbers}.pdf"

def upload_to_qiniu(local_file_path, access_key, secret_key, bucket_name, domain_of_bucket):
    """上传文件到七牛云并返回URL"""
    # 初始化Auth对象
    auth = Auth(access_key, secret_key)
    
    # 生成上传文件的key（文件名）
    key = os.path.basename(local_file_path)
    
    # 生成上传Token
    token = auth.upload_token(bucket_name, key, 3600)
    
    try:
        # 上传文件
        ret, info = put_file(token, key, local_file_path)
        
        if ret is not None:
            # 返回文件的完整URL
            file_url = f"http://{domain_of_bucket}/{key}"
            return file_url
        else:
            print(f"上传失败，错误信息：{info}")
            return None
    except Exception as e:
        print(f"上传过程出错：{str(e)}")
        return None

def convert_markdown_to_pdf(markdown_text, qiniu_config, output_dir=None, logger=None):
    """将Markdown文本转换为PDF文件并上传到七牛云"""
    if output_dir is None:
        output_dir = os.getcwd()
    os.makedirs(output_dir, exist_ok=True)

    # 生成唯一的文件名
    while True:
        filename = generate_random_filename()
        output_path = os.path.join(output_dir, filename)
        if not os.path.exists(output_path):
            break

    # 生成PDF
    pdf = MarkdownToPDF(output_path)
    pdf.process_markdown(markdown_text)
    pdf.save()
    if logger:
        logger.info(f"PDF已生成: {output_path}")

    # 上传到七牛云
    qiniu_url = upload_to_qiniu(
        output_path,
        qiniu_config['access_key'],
        qiniu_config['secret_key'],
        qiniu_config['bucket_name'],
        qiniu_config['domain']
    )
    
    if qiniu_url:
        if logger:
            logger.info(f"文件已上传到七牛云，访问地址：{qiniu_url}")
        # 删除本地文件
        os.remove(output_path)
        if logger:
            logger.info("本地临时文件已删除")
        return qiniu_url
    else:
        if logger:
            logger.error("文件上传失败")
        return None

def handler(args: Args[Input]) -> Output:
    """
    工具入口函数
    
    Parameters:
        args: 包含输入参数和日志记录器的参数对象
        args.input.inputMarkdown: 用户输入的markdown文本
        args.input.qiniu_Access_Key: 七牛云鉴权的AK
        args.input.qiniu_Secret_Key: 七牛云鉴权的SK
        args.input.qiniu_bucket_name: 文件存储的空间
        args.input.qiniu_cdn: 七牛云外链域名
        args.logger: 日志记录器实例
    
    Returns:
        Output: 包含PDF文件URL的输出对象
    """
    # 获取输入的Markdown文本
    markdown_text = args.input.inputMarkdown
    
    # 设置七牛云配置
    qiniu_config = {
        'access_key': args.input.qiniu_Access_Key,
        'secret_key': args.input.qiniu_Secret_Key,
        'bucket_name': args.input.qiniu_bucket_name,
        'domain': args.input.qiniu_cdn
    }
    
    # 设置临时输出目录
    output_dir = "/tmp/markdown_pdf"
    
    # 转换并上传PDF
    pdf_url = convert_markdown_to_pdf(markdown_text, qiniu_config, output_dir, args.logger)
    
    if pdf_url:
        return {"pdfUrl": pdf_url}
    else:
        raise Exception("PDF生成或上传失败")
```

---

## 数据分析代码

**输入参数示例图：**

按照这个命名规范即可复制所有代码

![](https://www.waytoagi.com/api/kb-media/LjSsb8fpaoLmPGxTK7nctnmlnWd)

- 复制需要把 我提供的代码中 前两行代码删掉，不要删掉 自己 新建插件的前两行，那是插件文件唯一指向

```python
from runtime import Args
from typings.Excel_change.Excel_change import Input, Output
import pandas as pd
import numpy as np
import json
import io
import requests
import copy
import time
from dataclasses import dataclass, field
from typing import Dict, List, Optional, Union, Any
from datetime import datetime

@dataclass
class PreprocessingConfig:
    drop_na: bool = False
    date_columns: List[str] = None
    date_format: str = "%Y-%m-%d"

@dataclass
class SortConfig:
    column: str
    ascending: bool = True

@dataclass
class DimensionConfig:
    name: str
    dimension_column: str
    metrics_columns: List[str]
    aggregation_methods: Dict[str, str]
    group_by_columns: List[str] = None
    sort_by: Optional[SortConfig] = None
    top_n: Optional[int] = None  # 将默认为None，代码中会处理为总行数
    filters: Dict[str, Any] = None

@dataclass
class TimeSeriesConfig:
    enabled: bool = False
    time_column: Optional[str] = None
    frequency: str = "M"
    metrics: List[str] = None
    aggregation: str = "sum"

@dataclass
class CorrelationConfig:
    enabled: bool = False
    columns: List[str] = None
    method: str = "pearson"

@dataclass
class AnalysisConfig:
    analysis_id: str
    analysis_name: str
    preprocessing: PreprocessingConfig
    dimensions: List[DimensionConfig]
    time_series_analysis: TimeSeriesConfig = None
    correlation_analysis: CorrelationConfig = None

class DataAnalyzer:
    def __init__(self, excel_url: str, config_json: str, logger=None):
        """初始化数据分析器
        Args:
            excel_url: Excel文件URL
            config_json: 配置JSON字符串
            logger: 日志记录器
        """
        self.excel_url = excel_url
        self.config_json = config_json
        self.config = None  # 将在load_data后设置
        self.df = None
        self.results = {}
        self.logger = logger or print

    def _download_file_with_retry(self, url, max_retries=3, timeout=60, chunk_size=8192):
        """使用分块下载和重试机制下载文件"""
        from requests.exceptions import RequestException
        
        for attempt in range(max_retries):
            try:
                self.logger(f"尝试下载文件 (尝试 {attempt+1}/{max_retries})...")
                
                # 设置超时和流式传输
                session = requests.Session()
                # 增加连接池大小和保持连接
                adapter = requests.adapters.HTTPAdapter(
                    pool_connections=5,
                    pool_maxsize=20,
                    max_retries=3
                )
                session.mount('http://', adapter)
                session.mount('https://', adapter)
                
                # 发送HEAD请求检查文件大小
                try:
                    head_response = session.head(url, timeout=timeout/2)
                    head_response.raise_for_status()
                    total_size = int(head_response.headers.get('content-length', 0))
                    if total_size:
                        self.logger(f"文件大小: {total_size/1024/1024:.2f} MB")
                except Exception as e:
                    self.logger(f"检查文件大小失败: {str(e)}，继续下载...")
                    total_size = 0
                
                # 开始下载
                response = session.get(url, stream=True, timeout=timeout)
                response.raise_for_status()
                
                # 如果HEAD请求未获取到大小，从GET响应获取
                if not total_size:
                    total_size = int(response.headers.get('content-length', 0))
                    if total_size:
                        self.logger(f"文件大小: {total_size/1024/1024:.2f} MB")
                
                # 使用字节IO流收集数据
                content = bytearray()
                downloaded = 0
                
                # 分块下载
                for chunk in response.iter_content(chunk_size=chunk_size):
                    if chunk:  # 过滤掉保持连接alive的空块
                        content.extend(chunk)
                        downloaded += len(chunk)
                        
                        # 每下载1MB记录一次进度
                        if downloaded % (1024*1024) == 0 and total_size:
                            progress = (downloaded / total_size) * 100
                            self.logger(f"下载进度: {progress:.1f}% ({downloaded/1024/1024:.2f}/{total_size/1024/1024:.2f} MB)")
                
                self.logger(f"文件下载完成，总大小: {len(content)/1024/1024:.2f} MB")
                return bytes(content)
                
            except RequestException as e:
                self.logger(f"下载失败 (尝试 {attempt+1}/{max_retries}): {str(e)}")
                if attempt < max_retries - 1:
                    # 指数退避策略
                    wait_time = 2 ** attempt
                    self.logger(f"等待 {wait_time} 秒后重试...")
                    time.sleep(wait_time)
                else:
                    self.logger("达到最大重试次数，下载失败")
                    raise

    def _parse_config(self, config_json: str, available_columns: List[str] = None) -> AnalysisConfig:
        """解析配置JSON字符串，并根据可用列名进行智能匹配
        Args:
            config_json: 配置JSON字符串
            available_columns: 可用的列名列表
        Returns:
            解析后的配置对象
        """
        config_dict = json.loads(config_json)
        
        # 如果有可用列名，进行智能匹配
        if available_columns:
            config_dict = self._auto_match_columns(config_dict, available_columns)
        
        # 转换预处理配置
        preprocessing = PreprocessingConfig(**config_dict['preprocessing'])
        
        # 转换维度配置
        dimensions = []
        for dim_dict in config_dict['dimensions']:
            if 'sort_by' in dim_dict and dim_dict['sort_by']:
                dim_dict['sort_by'] = SortConfig(**dim_dict['sort_by'])
            dimensions.append(DimensionConfig(**dim_dict))
        
        # 转换时间序列配置
        time_series = None
        if 'time_series_analysis' in config_dict and config_dict['time_series_analysis']:
            time_series = TimeSeriesConfig(**config_dict['time_series_analysis'])
        
        # 转换相关性分析配置
        correlation = None
        if 'correlation_analysis' in config_dict and config_dict['correlation_analysis']:
            correlation = CorrelationConfig(**config_dict['correlation_analysis'])
        
        return AnalysisConfig(
            analysis_id=config_dict['analysis_id'],
            analysis_name=config_dict['analysis_name'],
            preprocessing=preprocessing,
            dimensions=dimensions,
            time_series_analysis=time_series,
            correlation_analysis=correlation
        )

    def _auto_match_columns(self, config_dict: Dict, available_columns: List[str]) -> Dict:
        """智能匹配配置中的列名与实际列名"""
        available_columns = [str(col) for col in available_columns]
        updated_config = copy.deepcopy(config_dict)
        
        # 更新维度配置
        for dim_config in updated_config.get('dimensions', []):
            # 匹配维度列
            dim_col = dim_config.get('dimension_column')
            if dim_col and dim_col not in available_columns:
                matched_col = self._find_similar_column(dim_col, available_columns)
                if matched_col:
                    self.logger(f"将维度列 '{dim_col}' 匹配为 '{matched_col}'")
                    dim_config['dimension_column'] = matched_col
            
            # 匹配指标列
            metrics = dim_config.get('metrics_columns', [])
            agg_methods = dim_config.get('aggregation_methods', {})
            for i, metric in enumerate(metrics):
                if metric not in available_columns:
                    matched_col = self._find_similar_column(metric, available_columns)
                    if matched_col:
                        self.logger(f"将指标列 '{metric}' 匹配为 '{matched_col}'")
                        # 更新指标列
                        metrics[i] = matched_col
                        # 更新聚合方法
                        if metric in agg_methods:
                            agg_methods[matched_col] = agg_methods.pop(metric)
        
        # 更新时间序列配置
        ts_config = updated_config.get('time_series_analysis', {})
        if ts_config.get('enabled', False):
            time_col = ts_config.get('time_column')
            if time_col and time_col not in available_columns:
                matched_col = self._find_similar_column(time_col, available_columns)
                if matched_col:
                    self.logger(f"将时间列 '{time_col}' 匹配为 '{matched_col}'")
                    ts_config['time_column'] = matched_col
        
        # 更新相关性分析配置
        corr_config = updated_config.get('correlation_analysis', {})
        if corr_config.get('enabled', False):
            corr_columns = corr_config.get('columns', [])
            for i, col in enumerate(corr_columns):
                if col not in available_columns:
                    matched_col = self._find_similar_column(col, available_columns)
                    if matched_col:
                        self.logger(f"将相关性分析列 '{col}' 匹配为 '{matched_col}'")
                        corr_columns[i] = matched_col
        
        return updated_config

    def _find_similar_column(self, target: str, available_columns: List[str]) -> Optional[str]:
        """查找与目标列名最相似的列"""
        if not target or not isinstance(target, str):
            return None
        
        # 1. 精确匹配（忽略大小写）
        for col in available_columns:
            if str(col).lower() == target.lower():
                return col
        
        # 2. 包含匹配
        contained_matches = [col for col in available_columns 
                          if target.lower() in str(col).lower() or str(col).lower() in target.lower()]
        if contained_matches:
            return contained_matches[0]
        
        # 3. 简单相似度匹配
        max_similarity = 0
        best_match = None
        for col in available_columns:
            # 计算简单相似度（共同字符比例）
            common_chars = set(str(col).lower()) & set(target.lower())
            similarity = len(common_chars) / max(len(set(str(col).lower())), len(set(target.lower())))
            if similarity > max_similarity and similarity > 0.5:  # 相似度阈值
                max_similarity = similarity
                best_match = col
        
        return best_match

    def _detect_header_row(self, excel_content: bytes) -> int:
        """自动检测表头行"""
        # 常见的表头关键字
        header_keywords = ["序号", "时间", "日期", "姓名", "名称", "金额", "数量", "地址", "电话", "联系方式", "出单", "保单", "备注", "情况"]
        best_row = 0
        max_matches = 0
        
        # 尝试不同的行作为表头
        for i in range(10):  # 检查前10行
            try:
                df = pd.read_excel(io.BytesIO(excel_content), header=i, nrows=1)  # 只读取一行来检测
                columns = [str(col).lower() for col in df.columns]
                
                # 计算匹配的关键字数量
                matches = sum(1 for keyword in header_keywords 
                           if any(keyword.lower() in str(col).lower() for col in columns))
                
                # 如果匹配度更高，更新最佳行
                if matches > max_matches:
                    max_matches = matches
                    best_row = i
            except Exception as e:
                self.logger(f"检测表头第{i+1}行时出错: {str(e)}")
                continue
        
        self.logger(f"自动检测到表头在第{best_row+1}行，匹配关键字数量: {max_matches}")
        return best_row

    def load_data(self):
        """从URL加载Excel数据，处理合并单元格和多行表头"""
        try:
            # 使用改进的下载机制下载Excel文件
            self.logger(f"开始从URL下载Excel文件: {self.excel_url}")
            excel_content = self._download_file_with_retry(self.excel_url)
            
            # 自动检测表头行
            header_row = self._detect_header_row(excel_content)
            
            # 读取Excel，使用检测到的表头行
            self.logger("开始读取Excel数据...")
            
            # 检查文件大小，决定使用哪种读取方式
            file_size_mb = len(excel_content) / (1024 * 1024)
            if file_size_mb > 50:  # 大于50MB的文件
                self.logger(f"文件较大 ({file_size_mb:.2f} MB)，使用优化的读取方式")
                # 使用openpyxl引擎，可能对大文件处理更好
                self.df = pd.read_excel(
                    io.BytesIO(excel_content), 
                    header=header_row,
                    engine='openpyxl'
                )
            else:
                self.df = pd.read_excel(io.BytesIO(excel_content), header=header_row)
            
            # 清理列名 - 去除前后空格和特殊字符
            self.df.columns = [
                str(col).strip().replace('\n', ' ') if isinstance(col, str) else str(col)
                for col in self.df.columns
            ]
            
            # 删除全空行
            self.df = self.df.dropna(how='all')
            
            self.logger(f"数据加载完成，共 {len(self.df)} 行，{len(self.df.columns)} 列")
            self.logger(f"列名: {list(self.df.columns)}")
            
            # 根据实际列名解析配置
            self.config = self._parse_config(self.config_json, list(self.df.columns))
        except Exception as e:
            import traceback
            error_msg = f"加载数据失败: {str(e)}\n{traceback.format_exc()}"
            self.logger(error_msg)
            raise
        
        return self

    def preprocess_data(self):
        """数据预处理"""
        prep_config = self.config.preprocessing
        
        # 重要修改：不要使用drop_na，而是有选择地处理缺失值
        # 如果配置中设置了drop_na，我们只在这里记录，但不执行全局删除
        if prep_config.drop_na:
            self.logger("注意: 已禁用全局drop_na，将针对特定列处理缺失值")
        
        # 处理日期列
        if prep_config.date_columns:
            for col in prep_config.date_columns:
                if col in self.df.columns:
                    try:
                        self.df[col] = pd.to_datetime(self.df[col], format=prep_config.date_format, errors='coerce')
                    except Exception as e:
                        self.logger(f"警告: 转换日期列 '{col}' 时出错: {str(e)}")
        
        # 检查并转换数值列
        for dim_config in self.config.dimensions:
            for metric in dim_config.metrics_columns:
                if metric in self.df.columns:
                    # 检查数据类型
                    self.logger(f"{metric}列的数据类型: {self.df[metric].dtype}")
                    self.logger(f"{metric}列的缺失值数量: {self.df[metric].isna().sum()}")
                    self.logger(f"{metric}列的前5个值: {self.df[metric].head()}")
                    
                    # 转换为数值类型
                    try:
                        self.df[metric] = pd.to_numeric(self.df[metric], errors='coerce')
                        self.logger(f"已将{metric}列转换为数值类型")
                    except Exception as e:
                        self.logger(f"警告: 转换{metric}列为数值类型时出错: {str(e)}")
                    
                    # 填充缺失值为0
                    self.df[metric] = self.df[metric].fillna(0)
        
        # 检查维度列的唯一值
        for dim_config in self.config.dimensions:
            dim_col = dim_config.dimension_column
            if dim_col in self.df.columns:
                unique_values = self.df[dim_col].unique()
                self.logger(f"{dim_col}列的唯一值: {unique_values}")
                self.logger(f"{dim_col}列的缺失值数量: {self.df[dim_col].isna().sum()}")
                
                # 重要修改：确保维度列没有空值，用"未知"填充
                self.df[dim_col] = self.df[dim_col].fillna("未知")
        
        self.logger("数据预处理完成")
        return self

    def _apply_filters(self, df, filters):
        """应用过滤条件"""
        if not filters:
            return df
        
        filtered_df = df.copy()
        for column, condition in filters.items():
            if column not in filtered_df.columns:
                self.logger(f"警告: 过滤列 '{column}' 不存在，跳过此过滤条件")
                continue
            
            if isinstance(condition, list):
                filtered_df = filtered_df[filtered_df[column].isin(condition)]
            elif isinstance(condition, dict):
                if 'min' in condition:
                    filtered_df = filtered_df[filtered_df[column] >= condition['min']]
                if 'max' in condition:
                    filtered_df = filtered_df[filtered_df[column] <= condition['max']]
            else:
                filtered_df = filtered_df[filtered_df[column] == condition]
        
        return filtered_df

    def _generate_markdown_table(self, df):
        """生成Markdown表格"""
        if df.empty:
            return "**没有数据**"
        
        # 手动生成Markdown表格，因为to_markdown可能不可用
        headers = df.columns
        header_row = "| " + " | ".join(str(h) for h in headers) + " |"
        separator = "| " + " | ".join(["---"] * len(headers)) + " |"
        
        rows = []
        for _, row in df.iterrows():
            row_str = "| " + " | ".join(str(v) for v in row.values) + " |"
            rows.append(row_str)
        
        return "\n".join([header_row, separator] + rows)

    def analyze_dimension(self, dim_config):
        """分析单个维度"""
        self.logger(f"开始分析维度: {dim_config.name}")
        
        # 检查维度列是否存在
        if dim_config.dimension_column not in self.df.columns:
            error_msg = f"错误: 维度列 '{dim_config.dimension_column}' 不存在"
            self.logger(error_msg)
            return {
                "name": dim_config.name,
                "error": error_msg,
                "markdown": f"**{error_msg}**\n\n可用列: {list(self.df.columns)}"
            }
        
        # 检查指标列是否存在
        for metric in dim_config.metrics_columns:
            if metric not in self.df.columns:
                error_msg = f"错误: 指标列 '{metric}' 不存在"
                self.logger(error_msg)
                return {
                    "name": dim_config.name,
                    "error": error_msg,
                    "markdown": f"**{error_msg}**\n\n可用列: {list(self.df.columns)}"
                }
        
        # 应用过滤条件
        filtered_df = self._apply_filters(self.df, dim_config.filters)
        
        # 处理指标列中的缺失值
        for col in dim_config.metrics_columns:
            if pd.api.types.is_numeric_dtype(filtered_df[col]):
                filtered_df[col] = filtered_df[col].fillna(0)
        
        # 打印分组前的数据样例
        self.logger("分组前数据样例:")
        self.logger(filtered_df[[dim_config.dimension_column] + dim_config.metrics_columns].head())
        
        # 重要修改：检查是否有数据
        if filtered_df.empty:
            error_msg = "过滤后没有数据可分析"
            self.logger(error_msg)
            return {
                "name": dim_config.name,
                "error": error_msg,
                "markdown": f"**{error_msg}**"
            }
        
        # 准备分组列
        group_cols = [dim_config.dimension_column]
        if dim_config.group_by_columns:
            for col in dim_config.group_by_columns:
                if col in filtered_df.columns:
                    group_cols.append(col)
                else:
                    self.logger(f"警告: 分组列 '{col}' 不存在，将被忽略")
        
        # 执行聚合
        agg_dict = dim_config.aggregation_methods
        try:
            # 确保维度列不为空
            filtered_df = filtered_df.dropna(subset=[dim_config.dimension_column])
            
            # 打印分组和聚合信息
            self.logger(f"分组列: {group_cols}")
            self.logger(f"聚合方法: {agg_dict}")
            
            # 重要修改：直接使用pandas的pivot_table，更可靠地处理分组聚合
            result_df = pd.pivot_table(
                filtered_df,
                index=group_cols,
                values=list(agg_dict.keys()),
                aggfunc=agg_dict,
                fill_value=0
            ).reset_index()
            
            # 打印分组结果
            self.logger("分组聚合结果:")
            self.logger(result_df)
            
            # 重要修改：检查结果是否为空
            if result_df.empty:
                error_msg = "聚合后没有数据"
                self.logger(error_msg)
                return {
                    "name": dim_config.name,
                    "error": error_msg,
                    "markdown": f"**{error_msg}**"
                }
        except Exception as e:
            error_msg = f"聚合分析失败: {str(e)}"
            self.logger(error_msg)
            
            # 重要修改：尝试使用更简单的方法进行分组
            try:
                self.logger("尝试使用简化方法进行分组...")
                # 简单地计算每个维度值的指标总和
                result_data = []
                for dim_value in filtered_df[dim_config.dimension_column].unique():
                    row_data = {dim_config.dimension_column: dim_value}
                    for metric in dim_config.metrics_columns:
                        subset = filtered_df[filtered_df[dim_config.dimension_column] == dim_value]
                        row_data[metric] = subset[metric].sum()
                    result_data.append(row_data)
                
                result_df = pd.DataFrame(result_data)
                self.logger("简化分组结果:")
                self.logger(result_df)
                
                if result_df.empty:
                    return {
                        "name": dim_config.name,
                        "error": error_msg,
                        "markdown": f"**{error_msg}**"
                    }
            except:
                return {
                    "name": dim_config.name,
                    "error": error_msg,
                    "markdown": f"**{error_msg}**"
                }
        
        # 排序
        if dim_config.sort_by:
            sort_col = dim_config.sort_by.column
            if sort_col in result_df.columns:
                result_df = result_df.sort_values(
                    by=sort_col,
                    ascending=dim_config.sort_by.ascending
                )
                self.logger(f"已按{sort_col}列{'升序' if dim_config.sort_by.ascending else '降序'}排序")
            else:
                self.logger(f"警告: 排序列 '{sort_col}' 不存在，跳过排序")
        
        # 取Top N - 如果未指定，则使用全部行数
        if dim_config.top_n is not None:
            result_df = result_df.head(dim_config.top_n)
            self.logger(f"已取前{dim_config.top_n}行数据")
        
        # 生成Markdown表格
        markdown_table = self._generate_markdown_table(result_df)
        return {
            "name": dim_config.name,
            "markdown": markdown_table
        }

    def analyze_time_series(self):
        """时间序列分析"""
        ts_config = self.config.time_series_analysis
        if not ts_config or not ts_config.enabled:
            return None
        
        self.logger("开始时间序列分析")
        
        # 确保时间列存在
        if ts_config.time_column not in self.df.columns:
            error_msg = f"错误: 时间列 {ts_config.time_column} 不存在"
            self.logger(error_msg)
            return {
                "name": "时间序列分析",
                "error": error_msg,
                "markdown": f"**{error_msg}**\n\n可用列: {list(self.df.columns)}"
            }
        
        # 检查指标列是否存在
        for metric in ts_config.metrics:
            if metric not in self.df.columns:
                error_msg = f"错误: 指标列 '{metric}' 不存在"
                self.logger(error_msg)
                return {
                    "name": "时间序列分析",
                    "error": error_msg,
                    "markdown": f"**{error_msg}**\n\n可用列: {list(self.df.columns)}"
                }
        
        # 按时间分组并聚合
        df_ts = self.df.copy()
        
        # 确保时间列是日期类型
        if not pd.api.types.is_datetime64_any_dtype(df_ts[ts_config.time_column]):
            try:
                df_ts[ts_config.time_column] = pd.to_datetime(df_ts[ts_config.time_column], errors='coerce')
                self.logger(f"已将{ts_config.time_column}列转换为日期类型")
            except Exception as e:
                error_msg = f"时间列转换失败: {str(e)}"
                self.logger(error_msg)
                return {
                    "name": "时间序列分析",
                    "error": error_msg,
                    "markdown": f"**{error_msg}**"
                }
        
        # 处理指标列中的缺失值
        for col in ts_config.metrics:
            if pd.api.types.is_numeric_dtype(df_ts[col]):
                df_ts[col] = df_ts[col].fillna(0)
                self.logger(f"已将{col}列的缺失值填充为0")
        
        try:
            # 打印时间序列数据样例
            self.logger("时间序列数据样例:")
            self.logger(df_ts[[ts_config.time_column] + ts_config.metrics].head())
            
            # 设置时间索引并重采样
            df_ts = df_ts.set_index(ts_config.time_column)
            agg_dict = {metric: ts_config.aggregation for metric in ts_config.metrics}
            self.logger(f"时间序列聚合方法: {agg_dict}")
            
            resampled = df_ts.resample(ts_config.frequency).agg(agg_dict)
            result_df = resampled.reset_index()
            
            # 打印重采样结果
            self.logger("时间序列重采样结果:")
            self.logger(result_df)
            
            # 格式化日期列为字符串，便于显示
            result_df[ts_config.time_column] = result_df[ts_config.time_column].dt.strftime('%Y-%m-%d')
            
            # 生成Markdown表格
            markdown_table = self._generate_markdown_table(result_df)
            return {
                "name": "时间序列分析",
                "markdown": markdown_table
            }
        except Exception as e:
            error_msg = f"时间序列分析失败: {str(e)}"
            self.logger(error_msg)
            return {
                "name": "时间序列分析",
                "error": error_msg,
                "markdown": f"**{error_msg}**"
            }

    def analyze_correlation(self):
        """相关性分析"""
        corr_config = self.config.correlation_analysis
        if not corr_config or not corr_config.enabled:
            return None
        
        self.logger("开始相关性分析")
        
        # 检查相关性列是否存在
        missing_cols = [col for col in corr_config.columns if col not in self.df.columns]
        if missing_cols:
            error_msg = f"错误: 相关性分析列不存在: {missing_cols}"
            self.logger(error_msg)
            return {
                "name": "相关性分析",
                "error": error_msg,
                "markdown": f"**{error_msg}**\n\n可用列: {list(self.df.columns)}"
            }
        
        try:
            # 确保所有列都是数值类型
            corr_df = self.df[corr_config.columns].copy()
            for col in corr_config.columns:
                corr_df[col] = pd.to_numeric(corr_df[col], errors='coerce')
            
            # 打印相关性数据样例
            self.logger("相关性分析数据样例:")
            self.logger(corr_df.head())
            
            # 计算相关性
            corr_matrix = corr_df.corr(method=corr_config.method)
            self.logger("相关性矩阵:")
            self.logger(corr_matrix)
            
            # 重置索引，便于生成Markdown表格
            corr_result = corr_matrix.reset_index().rename(columns={'index': '变量'})
            
            # 生成Markdown表格
            markdown_table = self._generate_markdown_table(corr_result)
            return {
                "name": "相关性分析",
                "markdown": markdown_table
            }
        except Exception as e:
            error_msg = f"相关性分析失败: {str(e)}"
            self.logger(error_msg)
            return {
                "name": "相关性分析",
                "error": error_msg,
                "markdown": f"**{error_msg}**"
            }

    def run_analysis(self):
        """执行所有分析"""
        # 加载和预处理数据
        self.load_data().preprocess_data()
        
        # 分析各个维度
        dimension_results = []
        for dim_config in self.config.dimensions:
            result = self.analyze_dimension(dim_config)
            dimension_results.append(result)
        
        # 时间序列分析
        time_series_result = self.analyze_time_series()
        
        # 相关性分析
        correlation_result = self.analyze_correlation()
        
        # 汇总结果
        self.results = {
            "analysis_id": self.config.analysis_id,
            "analysis_name": self.config.analysis_name,
            "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            "dimensions": dimension_results,
            "time_series": time_series_result,
            "correlation": correlation_result
        }
        
        return self.results

def analyze_excel(excel_url: str, config_json: str, logger=None) -> Dict:
    """分析Excel数据的主函数
    Args:
        excel_url: Excel文件URL
        config_json: 配置JSON字符串
        logger: 日志记录器
    Returns:
        分析结果字典，包含Markdown表格
    """
    try:
        analyzer = DataAnalyzer(excel_url, config_json, logger)
        results = analyzer.run_analysis()
        
        # 构建完整的Markdown输出
        markdown_output = f"# {results['analysis_name']}\n\n"
        markdown_output += f"分析时间: {results['timestamp']}\n\n"
        
        # 添加维度分析结果
        for dim_result in results['dimensions']:
            markdown_output += f"## {dim_result['name']}\n\n"
            markdown_output += dim_result.get('markdown', f"**分析失败: {dim_result.get('error', '未知错误')}**") + "\n\n"
        
        # 添加时间序列分析结果
        if results['time_series']:
            markdown_output += f"## {results['time_series']['name']}\n\n"
            markdown_output += results['time_series'].get('markdown', f"**分析失败: {results['time_series'].get('error', '未知错误')}**") + "\n\n"
        
        # 添加相关性分析结果
        if results['correlation']:
            markdown_output += f"## {results['correlation']['name']}\n\n"
            markdown_output += results['correlation'].get('markdown', f"**分析失败: {results['correlation'].get('error', '未知错误')}**") + "\n\n"
        
        return {
            "status": "success",
            "markdown": markdown_output,
            "results": results
        }
    except requests.exceptions.RequestException as e:
        # 专门处理网络请求异常
        error_msg = f"下载Excel文件失败: {str(e)}\n\n请检查网络连接或文件URL是否有效。"
        logger(error_msg) if logger else print(error_msg)
        return {
            "status": "error",
            "markdown": f"**Excel文件下载失败**\n\n{error_msg}",
            "error": str(e)
        }
    except Exception as e:
        import traceback
        error_msg = f"分析失败: {str(e)}\n\n{traceback.format_exc()}"
        logger(error_msg) if logger else print(error_msg)
        return {
            "status": "error",
            "markdown": f"**{error_msg}**",
            "error": str(e),
            "traceback": traceback.format_exc()
        }

def handler(args: Args[Input]) -> Output:
    """
    工具入口函数
    
    Args:
        args: 包含输入参数的对象
        
    Returns:
        包含输出结果的对象
    """
    try:
        # 从输入参数中获取Excel URL和配置JSON
        excel_url = args.input.xlsxUrl
        config_json = args.input.profiles
        
        # 使用自定义logger记录日志
        def logger(message):
            args.logger.info(message)
        
        logger(f"开始处理Excel分析，URL: {excel_url}")
        
        # 执行Excel分析
        result = analyze_excel(excel_url, config_json, logger)
        
        # 返回Markdown格式的分析结果
        if result["status"] == "success":
            logger("分析成功完成")
            return {"Outmarkdown": result["markdown"]}
        else:
            logger(f"分析失败: {result.get('error', '未知错误')}")
            return {"Outmarkdown": f"**分析失败**\n\n{result['markdown']}"}
    
    except Exception as e:
        import traceback
        error_message = f"**处理过程中发生错误**\n\n错误信息: {str(e)}\n\n{traceback.format_exc()}"
        args.logger.error(error_message)
        return {"Outmarkdown": error_message}
```

---

## 数据抽样代码

**输入参数示例图：**

![](https://www.waytoagi.com/api/kb-media/FyI8bk4L8o77KwxSi3ScCHZtnho)

- 复制需要把前两行代码删掉

```python
from runtime import Args
from typings.Excel_cut.Excel_cut import Input, Output
import pandas as pd
import io
import urllib.request
import urllib.error
import time
import random
import socket
import zipfile
import re

"""
Each file needs to export a function named `handler`. This function is the entrance to the Tool.

Parameters:
args: parameters of the entry function.
args.input - input parameters, you can get test input value by args.input.xxx.
args.logger - logger instance used to print logs, injected by runtime.

Remember to fill in input/output in Metadata, it helps LLM to recognize and use tool.

Return: The return data of the function, which should match the declared output parameters.
"""

def handler(args: Args[Input]) -> Output:
    """
    获取Excel文件的随机50条数据并转换为Markdown表格
    
    Parameters:
        args: 包含输入参数的对象
            args.input.xlsx_url: Excel文件的URL链接
        
    Returns:
        包含Markdown表格和总行数的输出对象
    """
    try:
        # 获取Excel文件URL
        xlsx_url = args.input.xlsx_url
        args.logger.info(f"正在处理Excel文件: {xlsx_url}")
        
        # 验证URL是否指向Excel文件
        if not is_valid_excel_url(xlsx_url):
            return {
                "outMarkdown": f"## 错误\n\nURL不是有效的Excel文件链接: {xlsx_url}\n\n请确保URL以.xls、.xlsx、.xlsm或.csv结尾，或包含明确指向Excel文件的路径。",
                "count": 0
            }
        
        # 下载文件
        try:
            excel_content = download_with_retry(xlsx_url, logger=args.logger)
            
            # 验证下载的内容是否为有效的Excel文件
            file_type = detect_file_type(excel_content)
            args.logger.info(f"检测到文件类型: {file_type}")
            
            if file_type == "unknown":
                # 尝试检查是否为HTML错误页面
                if is_html_content(excel_content):
                    error_msg = extract_error_from_html(excel_content)
                    return {
                        "outMarkdown": f"## 错误\n\n服务器返回了HTML页面而不是Excel文件。可能的原因：\n\n- 需要登录或授权\n- 文件不存在\n- URL重定向到了错误页面\n\n服务器消息: {error_msg}",
                        "count": 0
                    }
                else:
                    return {
                        "outMarkdown": f"## 错误\n\n下载的文件不是有效的Excel文件。请检查URL是否正确。",
                        "count": 0
                    }
        except Exception as e:
            error_message = f"下载文件时出错: {str(e)}"
            args.logger.error(error_message)
            return {
                "outMarkdown": f"## 错误\n\n{error_message}",
                "count": 0
            }
        
        # 根据文件类型选择适当的读取方法
        try:
            if file_type == "csv":
                args.logger.info("使用CSV读取器...")
                df = pd.read_csv(io.BytesIO(excel_content))
            elif file_type in ["xlsx", "xlsm"]:
                args.logger.info("使用Excel读取器...")
                df = pd.read_excel(io.BytesIO(excel_content))
            elif file_type == "xls":
                args.logger.info("使用旧版Excel读取器...")
                df = pd.read_excel(io.BytesIO(excel_content), engine='xlrd')
            else:
                return {
                    "outMarkdown": f"## 错误\n\n不支持的文件类型: {file_type}",
                    "count": 0
                }
        except Exception as e:
            error_message = f"读取Excel数据时出错: {str(e)}"
            args.logger.error(error_message)
            return {
                "outMarkdown": f"## 错误\n\n{error_message}",
                "count": 0
            }

        # 获取总行数
        total_rows = len(df)
        args.logger.info(f"总行数: {total_rows}")
        
        # 清理列名 - 去除前后空格和特殊字符
        df.columns = [
            str(col).strip().replace('\n', ' ') if isinstance(col, str) else str(col)
            for col in df.columns
        ]
        
        # 随机打乱数据并获取前50条
        df_shuffled = df.sample(frac=1, random_state=None)
        df_head = df_shuffled.head(50)
        args.logger.info(f"成功读取随机抽样数据，显示前{min(50, len(df))}行")
        
        # 转换为Markdown表格
        markdown_table = generate_markdown_table(df_head)
        
        # 添加一些元信息
        markdown_output = f"# Excel数据预览\n\n"
        markdown_output += markdown_table
        
        return {
            "outMarkdown": markdown_output,
            "count": total_rows
        }

    except Exception as e:
        error_message = f"处理Excel文件时出错: {str(e)}"
        args.logger.error(error_message)
        return {
            "outMarkdown": f"## 错误\n\n{error_message}",
            "count": 0
        }

def is_valid_excel_url(url):
    """检查URL是否可能指向Excel文件"""
    excel_patterns = [r'\.xlsx?$', r'\.xlsm$', r'\.csv$', r'/.*\.xlsx?', r'/.*\.xlsm', r'/.*\.csv']
    return any(re.search(pattern, url, re.IGNORECASE) for pattern in excel_patterns)

def detect_file_type(content):
    """检测文件类型"""
    # 检查是否为XLSX/XLSM (ZIP格式)
    try:
        with zipfile.ZipFile(io.BytesIO(content)) as zf:
            if any('xl/workbook.xml' in name for name in zf.namelist()):
                return "xlsx"  # 或xlsm，这里简化处理
    except zipfile.BadZipFile:
        pass
    
    # 检查是否为XLS (OLE2格式)
    if content.startswith(b'\xd0\xcf\x11\xe0'):
        return "xls"
    
    # 检查是否为CSV
    try:
        text_sample = content[:1000].decode('utf-8')
        if ',' in text_sample and '\n' in text_sample:
            return "csv"
    except:
        pass
    
    return "unknown"

def is_html_content(content):
    """检查内容是否为HTML"""
    try:
        text_sample = content[:1000].decode('utf-8', errors='ignore').lower()
        return '<html' in text_sample or '<!doctype html' in text_sample
    except:
        return False

def extract_error_from_html(content):
    """从HTML内容中提取可能的错误信息"""
    try:
        text = content.decode('utf-8', errors='ignore')
        # 尝试提取常见的错误信息模式
        error_patterns = [
            r'<title>(.*?)</title>',
            r'<h1>(.*?)</h1>',
            r'error.*?>(.*?)<',
            r'exception.*?>(.*?)<'
        ]
        
        for pattern in error_patterns:
            matches = re.findall(pattern, text, re.IGNORECASE)
            if matches:
                return matches[0].strip()
        
        return "无法提取错误信息"
    except:
        return "无法解析HTML内容"

def download_with_retry(url, max_retries=3, initial_delay=1, max_delay=10, logger=None):
    """
    完整下载文件（带重试机制）
    """
    if logger:
        logger.info(f"开始下载文件: {url}")
    
    retry_count = 0
    delay = initial_delay
    
    # 设置超时时间
    socket.setdefaulttimeout(20)  # 20秒超时
    
    while retry_count < max_retries:
        try:
            # 创建请求对象，添加用户代理和其他可能需要的头信息
            req = urllib.request.Request(
                url,
                headers={
                    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                    'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, text/csv, */*'
                }
            )
            
            # 执行请求
            with urllib.request.urlopen(req) as response:
                content = response.read()
                
                if logger:
                    logger.info(f"文件下载成功，大小: {len(content)} 字节")
                return content
            
        except Exception as e:
            retry_count += 1
            
            if retry_count >= max_retries:
                if logger:
                    logger.error(f"下载失败，已达到最大重试次数: {str(e)}")
                raise Exception(f"下载文件失败，已重试{max_retries}次: {str(e)}")
            
            delay = min(delay * 2, max_delay) * (0.5 + random.random())
            
            if logger:
                logger.warning(f"下载失败，将在{delay:.2f}秒后重试 ({retry_count}/{max_retries}): {str(e)}")
            
            time.sleep(delay)

def generate_markdown_table(df):
    """
    将DataFrame转换为Markdown表格
    
    Parameters:
        df: 要转换的DataFrame
        
    Returns:
        Markdown格式的表格字符串
    """
    if df.empty:
        return "**没有数据**"
    
    # 限制列数，避免表格过宽
    if len(df.columns) > 30:
        df = df.iloc[:, :30]
        note = "\n\n*注: 表格仅显示前30列数据，原数据列数过多*"
    else:
        note = ""
    
    # 处理数据，确保所有值都是字符串且长度适中
    def format_cell(val):
        # 处理None值
        if pd.isna(val):
            return ""
        
        # 转换为字符串并限制长度
        s = str(val)
        if len(s) > 30:  # 减少单元格最大长度
            return s[:27] + "..."
        return s
    
    # 手动生成Markdown表格
    headers = df.columns
    header_row = "| " + " | ".join(str(h) for h in headers) + " |"
    separator = "| " + " | ".join(["---"] * len(headers)) + " |"
    
    rows = []
    for _, row in df.iterrows():
        formatted_values = [format_cell(v) for v in row.values]
        row_str = "| " + " | ".join(formatted_values) + " |"
        rows.append(row_str)
    
    return "\n".join([header_row, separator] + rows) + note
```

---

# 六，提示词

## 配置文件提示词工程

```markdown
# Role: 资深数据分析配置专家 & 运营分析师

## Task
基于用户提供的数据，进行深度运营分析，并生成5个分析维度的配置文件(profiles1-5)，使用指定的JSON模板结构。

## Process
1. **请提供以下数据信息**：
   - 数据字段列表及说明
   - 2-3行数据样本
   - 相关业务背景（可选）

2. **我将进行如下分析**：
   - 识别数据特征和业务价值
   - 设计深度运营分析维度
   - 构建多层分析结构
   - 生成对应配置文件

## Configuration Template
'''python
{
    "analysis_id": "string",
    "analysis_name": "string",
    "preprocessing": {
        "drop_na": boolean,
        "date_columns": ["string"],
        "date_format": "string"
    },
    "dimensions": [{
        "name": "string",
        "dimension_column": "string",
        "metrics_columns": ["string"],
        "aggregation_methods": {
            "column": "method"
        },
        "sort_by": {
            "column": "string",
            "ascending": boolean
        }
    }],
    "time_series_analysis": {
        "enabled": boolean,
        "time_column": "string",
        "frequency": "string",
        "metrics": ["string"],
        "aggregation": "string"
    },
    "correlation_analysis": {
        "enabled": boolean,
        "columns": ["string"]
    }
}
'''

## Output Format
我将输出：

1. **数据分析概要**：
   - 数据特征说明
   - 可用分析维度
   - 建议分析方向

2. **五个配置文件变量**：
'''python
profiles1 = {...} # 核心业务分析配置
profiles2 = {...} # 深度运营分析配置
profiles3 = {...} # 用户洞察分析配置
profiles4 = {...} # 效能评估分析配置
profiles5 = {...} # 风险监控分析配置
```

## 图表提示词工程

```markdown

**Role: ECharts智能可视化助手

Description: 将Markdown表格数据转换为最适合的ECharts图表配置代码。

Input Format:
| Header1 | Header2 | Header3 |
|---------|---------|---------|
| Data1   | Data2   | Data3   |

Analysis Rules:
1. 数据类型判断:
   - 数值列: 包含数字的列
   - 时间列: 包含日期/时间的列
   - 类别列: 包含文本分类的列

2. 图表类型选择:

基础图表:
- 数值对比 → line(折线图)/bar(柱状图)
- 占比分析 → pie(饼图)/doughnut(环形图)
- 散点分布 → scatter(散点图)
- 区域图表 → area(面积图)

复合图表:
- 时间趋势 + 数值对比 → line + bar(折线柱状混合)
- 多维数据对比 → radar(雷达图)
- 股票数据分析 → candlestick(K线图)
- 树形结构数据 → tree(树图)/treemap(矩形树图)

数据关系:
- 层级数据 → sunburst(旭日图)
- 流向关系 → sankey(桑基图)
- 关系网络 → graph(关系图)
- 平行分析 → parallel(平行坐标图)

地理数据:
- 地理可视化 → map(地图)
- 热力分布 → heatmap(热力图)

Output Format: 仅输出一个完整的ECharts配置对象，格式为单行JSON

Example Input:
| 月份 | 访问量 |
|------|--------|
| 1月  | 120    |
| 2月  | 132    |
| 3月  | 101    |

Example Output:
{"title":{"text":"网站访问量趋势"},"tooltip":{"trigger":"axis"},"legend":{"data":["访问量"],"top":"bottom"},"xAxis":{"type":"category","boundaryGap":false,"data":["1月","2月","3月","4月","5月","6月","7月"]},"yAxis":{"type":"value","axisLabel":{"formatter":"{value} 次"}},"series":[{"name":"访问量","type":"line","data":[120,132,101,134,90,230,210]}]}

Constraints:
1. 仅输出单行JSON格式的ECharts配置代码
2. 不包含任何注释或说明文字
3. 确保配置代码的完整性和有效性**
```

# 七，常见问题

## 数据维度分析LLM输出为null

![](https://www.waytoagi.com/api/kb-media/AWwObsi8OoB6mzxOQ8tcfei5nBb)

解决方法：调整token限制，尽量调高

![](https://www.waytoagi.com/api/kb-media/DoxebWqnPolzP7xVfN9cpkAOnTf)

---

## 学习交流

![](https://www.waytoagi.com/api/kb-media/Q4AGbDLzzo8FJcxzqklcYnMznbk)
