# Excel Sort

> |

- **Type:** Skill
- **Install:** `agentstack add skill-yuyy2004-excel-skills-excel-sort`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [YuYY2004](https://agentstack.voostack.com/s/yuyy2004)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** MIT
- **Upstream author:** [YuYY2004](https://github.com/YuYY2004)
- **Source:** https://github.com/YuYY2004/excel-skills/tree/main/claude/skills/excel-sort

## Install

```sh
agentstack add skill-yuyy2004-excel-skills-excel-sort
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

> This skill follows [[excel-safe-workflow]] four-step method. Must scout and confirm sort column and range before execution, and verify correct order after.
> 本技能遵循 [[excel-safe-workflow]] 四步法。执行前必须勘察确认排序列和范围，执行后验证顺序正确。

# Excel Sort / Excel 排序

## 第零步：需求解析

| 要素 | 常见表述 | 默认值 |
|------|---------|--------|
| **排序列** | "按公开日排序""E列排序" | 必须明确 |
| **方向** | "从小到大""升序""asc" → asc；"从大到小""降序""desc" → desc | `asc` |
| **多列排序** | "先按A列再按B列" | 按优先级排列 |
| **数据范围** | 默认包含表头行（第1行），自动识别数据区 | 有表头 |

### 解析示例

| 用户说 | 提取 |
|--------|------|
| "按公开日升序排列" | 列=公开日, asc |
| "按金额从大到小排序" | 列=金额, desc |
| "先按类别排，再按日期排" | 列=[类别,日期], 默认asc |

## 第一步：勘察

```python
from openpyxl import load_workbook

FILE = '目标文件.xlsx'
wb = load_workbook(FILE)
ws = wb.active
print(f'{ws.max_row}行 x {ws.max_column}列')

# 定位排序列
print('\n=== 表头 ===')
for col_idx in range(1, ws.max_column + 1):
    h = ws.cell(row=1, column=col_idx).value
    if h:
        print(f'  列{col_idx}: {h}')

# 确认数据类型
sort_col = None  # 排序列号
print(f'\n排序列数据样本:')
for row in [2, 3, 4, ws.max_row // 2, ws.max_row]:
    v = ws.cell(row=row, column=sort_col).value
    print(f'  行{row}: {type(v).__name__} = {repr(v)[:40]}')

wb.close()
```

## 第二步：执行

**策略：大文件统一走「读格式→pandas处理→刷回格式」三步。**

```python
import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, Alignment, PatternFill
from copy import copy

FILE = '目标文件.xlsx'
SORT_COLS = [('列名或列号', 'asc')]  # asc/desc
HEADER_ROW = 1

# ====== 第一步：读取格式 ======
print('① 读取格式...')
wb = load_workbook(FILE)
ws = wb.active

header_formats, data_formats, col_widths = {}, {}, {}
for col in range(1, ws.max_column + 1):
    header_formats[col] = {
        'font': copy(ws.cell(row=HEADER_ROW, column=col).font),
        'alignment': copy(ws.cell(row=HEADER_ROW, column=col).alignment),
        'fill': copy(ws.cell(row=HEADER_ROW, column=col).fill),
    }
    data_formats[col] = {
        'font': copy(ws.cell(row=HEADER_ROW + 1, column=col).font),
        'alignment': copy(ws.cell(row=HEADER_ROW + 1, column=col).alignment),
        'fill': copy(ws.cell(row=HEADER_ROW + 1, column=col).fill),
    }
    col_letter = chr(64 + col) if col  prev:
                print(f'  ❌ 行{row}: {v} > {prev}')
                ok = False
        if v is not None:
            prev = v
        print(f'  行{row}: {v}')
    print(f'  {"✅" if ok else "❌"}')

wb.close()
```

## 注意事项

1. **None 值**始终排到最后（无论升序降序）
2. **表头**不参与排序，固定在原位
3. **公式列排序**会导致引用错乱——勘察时检查排序列是否为公式，如是则先转为值再排
4. **格式保留 vs 速度**：
   -  5万行：**询问用户**——「格式保留需要约 N 分钟，是否保留原格式？」
5. **列内格式差异**：格式以数据首行为模板统一应用。如列内格式不一致，统一后会丢失差异
6. **操作前必备份**：遵循 [[excel-safe-workflow]] 第零步——操作前自动备份（时间戳命名），成功后保留最新3份，失误后立即删除损坏文件并从备份恢复

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [YuYY2004](https://github.com/YuYY2004)
- **Source:** [YuYY2004/excel-skills](https://github.com/YuYY2004/excel-skills)
- **License:** MIT

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-yuyy2004-excel-skills-excel-sort
- Seller: https://agentstack.voostack.com/s/yuyy2004
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
