# XLSX Text Extraction

> 使用 openpyxl 从 Microsoft Excel（.xlsx）工作簿中抽取表格数据。

Source: https://docs.sommatic.ai/zh/nodes/ai.xlsx.extract.text/

- 标识: `ai.xlsx.extract.text`
- 类别: AI
- 版本: 1.0.0
- 状态: 可用
- 执行方式: async

使用 openpyxl 从 Microsoft Excel（.xlsx）工作簿中抽取表格数据。

按工作簿顺序遍历每个非空工作表，并将每个工作表渲染为独立的 markdown 表格，生成单一的规范化文本输出，可直接用于下游 LLM、向量索引或分类。

**功能特性：**
- **逐表渲染：** 每个工作表以其名称作为标题输出，后接其已用区域的 markdown 表格。
- **格式化的单元格值：** 应用工作簿中数字、日期和百分比的显示格式，使抽取的文本与用户在 Excel 中看到的一致。
- **合并单元格与冻结窗格：** 合并区域折叠为其锚点值并加注；冻结的表头行会被标记，确保在下游截断时仍得以保留。
- **空工作表检测：** 没有数据的工作表会被跳过，并在输出元数据中报告，而不是输出空章节。
- **元数据：** 工作簿属性（标题、作者、创建日期），以及每个工作表的统计信息（行数、列数、已用区域）。

## 配置

该节点没有配置项。

配置中会显示通用执行设置，但该节点目前不执行重试（`retryOnFail`、`maxTries`）。所有节点均未实现 `continueOnFail`。

## 输出端口

- `extracted` (默认): Extracted
- `empty`: Empty
- `error`: Error

## 输入契约

- `content_base64` (string, 可选)
- `file_path` (string, 可选)

## 输出契约

- `text` (string, 可选)
- `chars` (number, 可选)
- `empty` (boolean, 可选)
- `method` (string, 可选)
- `metadata` (object, 可选)

## 在表达式中

后续节点可通过 `$("XLSX Text Extraction").item.json.<路径>` 读取此节点输出中的内容（请把 `XLSX Text Extraction` 换成你的节点标签）。**Editor** 标记工作流编辑器在 Previous Nodes 中提示的路径（输出契约）；**Worker** 标记 worker 实际通过 `extracted` 返回的路径，依据“端口”一节所示的输出。

- `$("XLSX Text Extraction").item.json.text` (string) = `"## Sheet: Sales\n\n| Region | Total |\n| ---…"`
- `$("XLSX Text Extraction").item.json.chars` (number) = `84`
- `$("XLSX Text Extraction").item.json.empty` (boolean) = `false`
- `$("XLSX Text Extraction").item.json.method` (string) = `"openpyxl"`
- `$("XLSX Text Extraction").item.json.metadata` (object) = `{…}`
- `$("XLSX Text Extraction").item.json.metadata.sheets_total` (number) = `2` (编辑器不提示)
- `$("XLSX Text Extraction").item.json.metadata.sheets_with_data` (number) = `1` (编辑器不提示)
- `$("XLSX Text Extraction").item.json.metadata.sheet_names` (array) = `[…] (2)` (编辑器不提示)


## 工作原理

使用 openpyxl 读取 .xlsx 工作簿，并将每个含数据的工作表渲染为 `## Sheet: <name>` 标题下的 Markdown 表格。

1. 解析节点配置：配置键中的表达式会基于本次运行求值；传入条目按原样使用。
2. 先从配置、再从传入条目读取 `content_base64` 或 `file_path`。两者都没有时返回 `error`。
3. 以值模式打开工作簿：公式单元格返回文件中缓存的值，而不是公式本身。
4. 按工作簿顺序处理每个工作表：删除完全空白的行，将各行补齐到最宽行的列数，用剩余的第一行作为表头，并转义单元格中的 `|`。
5. 没有数据的工作表会被跳过，只在 `metadata` 中计数。
6. 脚本失败时返回 `error`，附带 Python 消息和 stderr。否则 `empty: true` 从 `empty` 输出，其他结果从 `extracted` 输出。

## 在工作流中

### 节点

```json
{
  "node_id": "node-xlsx-text",
  "label": "Read workbook",
  "operator_slug": "ai.xlsx.extract.text",
  "operator_version": "1.0.0",
  "config": {
    "execution": {
      "timeout_ms": 120000
    }
  }
}
```

### Envelope

```json
{
  "ok": true,
  "port": "extracted",
  "data": {
    "text": "## Sheet: Sales\n\n| Region | Total |\n| --- | --- |\n| North | 1200 |\n| South | 980.5 |",
    "chars": 84,
    "empty": false,
    "method": "openpyxl",
    "metadata": {
      "sheets_total": 2,
      "sheets_with_data": 1,
      "sheet_names": [
        "Sales",
        "Notes"
      ]
    }
  }
}
```

## 输出端口 (代码中的行为)

### `extracted`

至少有一个工作表含有数据。

```json
{
  "text": "## Sheet: Sales\n\n| Region | Total |\n| --- | --- |\n| North | 1200 |\n| South | 980.5 |",
  "chars": 84,
  "empty": false,
  "method": "openpyxl",
  "metadata": {
    "sheets_total": 2,
    "sheets_with_data": 1,
    "sheet_names": [
      "Sales",
      "Notes"
    ]
  }
}
```

### `empty`

没有任何工作表含有数据。结构相同，`text: ""` 且 `empty: true`。

```json
{
  "text": "",
  "chars": 0,
  "empty": true,
  "method": "openpyxl",
  "metadata": {
    "sheets_total": 1,
    "sheets_with_data": 0,
    "sheet_names": [
      "Sheet1"
    ]
  }
}
```

### `error`

缺少输入或脚本失败。`data` 为 `{ error }` 或 `{ error, stderr }`。

```json
{
  "error": "File is not a zip file",
  "stderr": ""
}
```

## 代码中的行为

- `execution.timeout_ms`: Python 子进程的超时时间。未设置时代码使用 120000 毫秒（schema 显示的默认值为 300000）。
- `content_base64 / file_path`: 它们未在配置 schema 中声明，但会先于传入条目从配置读取。可用表达式指向文件，例如 `{{ $json.attachment.content_base64 }}`。

## 错误

| 消息 | 端口 | 原因与处理 |
| --- | --- | --- |
| `Either content_base64 or file_path is required.` | `error` | 配置和传入条目中都没有 `content_base64` 或 `file_path`。请从上一个节点映射文件。 |
| `Either content_base64 or file_path is required` | `error` | 当 `file_path` 在编排器主机上不存在时由 Python 脚本抛出。数据中还包含 `stderr`。 |
| `<exception message from the Python library>` | `error` | 无法将文件读取为.xlsx 工作簿（文件损坏、已加密或为其他格式）。详情见 `data.stderr`。 |
| `Python timed out after <timeout_ms>ms` | `error` | 脚本超过了 `execution.timeout_ms`。请调大该值或减少处理的页数。 |
| `Python runtime not available (ENOENT)` | `error` | 编排器主机上没有可用的 Python 解释器。 |

## 说明与限制

- 单元格值以 Python 纯字符串写出，而非 Excel 显示格式：日期输出为 `2026-01-15 00:00:00`，25% 输出为 `0.25`。
- 公式不会被计算。未保存缓存值的工作簿（例如由脚本生成）中，公式单元格将为空。
- 尚未实现（尽管描述中提到）：合并单元格和冻结窗格的标注，以及工作簿属性（标题、作者、创建日期）。
- 仅支持 .xlsx；旧版 .xls 文件会失败。
- `file_path` 是编排器主机上的路径。两者同时存在时以 `content_base64` 为准。
- 提取在 Python 子进程中运行。首次使用时，编排器会创建虚拟环境并安装固定版本的依赖，可能需要数分钟；之后的运行会复用该环境。
- Python 结果的输出上限为 50 MB；超过后节点从 `error` 端口输出。
- 引擎不会对此节点应用 `execution.retryOnFail`、`maxTries`、`waitBetweenTries` 或 `continueOnFail`。请通过连接 `error` 端口处理失败。


## 契约（JSON Schema）

### All (`*.definition.js`)

```json
{
  "slug": "ai.xlsx.extract.text",
  "name": "XLSX Text Extraction",
  "category": "ai",
  "version": "1.0.0",
  "description": "Extracts tabular data from Microsoft Excel (.xlsx) workbooks using openpyxl.\n\n  Iterates every non-empty sheet in workbook order and renders each as a standalone markdown table, producing a single normalized text output suitable for downstream LLM consumption, vector indexing, or direct classification.\n\n  **Features:**\n  - **Per-sheet rendering:** Each sheet is emitted with its name as a header followed by a markdown table of its used range.\n  - **Formatted cell values:** Applies the workbook's display formats for numbers, dates, and percentages so the extracted text matches what a user sees in Excel.\n  - **Merged cells and frozen panes:** Merged regions are collapsed to their anchor value and annotated; frozen header rows are marked so they survive downstream truncation.\n  - **Empty sheet detection:** Sheets with no data are skipped and reported in the output metadata rather than emitted as empty sections.\n  - **Metadata:** Workbook properties (title, author, creation date) plus per-sheet statistics (rows, columns, used range).",
  "capabilities": [
    "xlsx",
    "office",
    "excel",
    "spreadsheet",
    "text-extraction"
  ],
  "config_schema": {
    "type": "object",
    "properties": {
      "execution": {
        "type": "object",
        "title": "Execution Settings",
        "properties": {
          "alwaysOutputData": {
            "type": "boolean",
            "title": "Always Output Data",
            "description": "Always output data, even on error (if configured).",
            "default": false
          },
          "retryOnFail": {
            "type": "boolean",
            "title": "Retry On Fail",
            "description": "Retry the execution if it fails.",
            "default": false
          },
          "maxTries": {
            "type": "integer",
            "title": "Max Retries",
            "description": "Number of retries.",
            "default": 3,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "waitBetweenTries": {
            "type": "integer",
            "title": "Wait Between Retries (ms)",
            "default": 1000,
            "displayOptions": {
              "show": {
                "retryOnFail": [
                  true
                ]
              }
            }
          },
          "continueOnFail": {
            "type": "boolean",
            "title": "Continue On Fail",
            "description": "Do not crash workflow on error.",
            "default": false
          },
          "timeout_ms": {
            "type": "integer",
            "title": "Timeout (ms)",
            "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
            "default": 300000
          }
        }
      }
    }
  },
  "input_contract_schema": {
    "type": "object",
    "properties": {
      "content_base64": {
        "type": "string"
      },
      "file_path": {
        "type": "string"
      }
    }
  },
  "output_contract_schema": {
    "type": "object",
    "properties": {
      "text": {
        "type": "string"
      },
      "chars": {
        "type": "number"
      },
      "empty": {
        "type": "boolean"
      },
      "method": {
        "type": "string"
      },
      "metadata": {
        "type": "object"
      }
    }
  },
  "ports": [
    {
      "port_id": "extracted",
      "label": "Extracted",
      "is_default": true,
      "supports_condition": true
    },
    {
      "port_id": "empty",
      "label": "Empty",
      "is_default": false,
      "supports_condition": true
    },
    {
      "port_id": "error",
      "label": "Error",
      "is_default": false,
      "supports_condition": false
    }
  ],
  "execution_mode": "async",
  "tags": [
    "ai",
    "xlsx",
    "office",
    "excel",
    "spreadsheet",
    "text"
  ],
  "is_stateful": false,
  "publisher": {
    "identity": "org_sommatic_ai",
    "profile": {
      "name": "Sommatic AI",
      "verified": true,
      "url": "https://me.veripass.com/sommatic",
      "logo_url": null
    }
  }
}
```

### config_schema

```json
{
  "type": "object",
  "properties": {
    "execution": {
      "type": "object",
      "title": "Execution Settings",
      "properties": {
        "alwaysOutputData": {
          "type": "boolean",
          "title": "Always Output Data",
          "description": "Always output data, even on error (if configured).",
          "default": false
        },
        "retryOnFail": {
          "type": "boolean",
          "title": "Retry On Fail",
          "description": "Retry the execution if it fails.",
          "default": false
        },
        "maxTries": {
          "type": "integer",
          "title": "Max Retries",
          "description": "Number of retries.",
          "default": 3,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "waitBetweenTries": {
          "type": "integer",
          "title": "Wait Between Retries (ms)",
          "default": 1000,
          "displayOptions": {
            "show": {
              "retryOnFail": [
                true
              ]
            }
          }
        },
        "continueOnFail": {
          "type": "boolean",
          "title": "Continue On Fail",
          "description": "Do not crash workflow on error.",
          "default": false
        },
        "timeout_ms": {
          "type": "integer",
          "title": "Timeout (ms)",
          "description": "Max execution time for this node before it is killed, in milliseconds. Honored by long-running operators (e.g. OCR/extraction, inline code). Default 300000 (5 min).",
          "default": 300000
        }
      }
    }
  }
}
```

### input_contract_schema

```json
{
  "type": "object",
  "properties": {
    "content_base64": {
      "type": "string"
    },
    "file_path": {
      "type": "string"
    }
  }
}
```

### output_contract_schema

```json
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    },
    "chars": {
      "type": "number"
    },
    "empty": {
      "type": "boolean"
    },
    "method": {
      "type": "string"
    },
    "metadata": {
      "type": "object"
    }
  }
}
```

### ports

```json
[
  {
    "port_id": "extracted",
    "label": "Extracted",
    "is_default": true,
    "supports_condition": true
  },
  {
    "port_id": "empty",
    "label": "Empty",
    "is_default": false,
    "supports_condition": true
  },
  {
    "port_id": "error",
    "label": "Error",
    "is_default": false,
    "supports_condition": false
  }
]
```
