---
name: php186-skill-62854
description: "Parse MySQL 8.0 DDL scripts and export table structures to Excel format. Use when users need to convert MySQL CREATE TABLE statements into structured Excel files with field names, data types, lengths, and precision. Supports batch processing of multiple tables, with each table as a separate sheet. Ideal for database documentation, data dictionary generation, and schema analysis tasks."
---

# kashen-mysql DDLtoExcel

## MySQL DDL to Excel

 

将 MySQL 8.0 DDL 脚本解析并导出为 Excel 格式的表结构文档。

 

## 功能

 

- 解析 MySQL ` CREATE TABLE ` 语句
- 提取字段名、数据类型、长度、精度
- 每个表生成一个独立的 Excel Sheet
- 支持批量处理多个表

 

## 输出格式

 

每个 Sheet 的格式如下：

 

| 行号 | 内容 |
| --- | --- |
| 第1行 | 表名：` 表名：table_name ` |
| 第2行 | 表头：` 属性名 `、` 数据类型 `、` 长度 `、` 精度 ` |
| 第3行+ | 实际数据：字段信息 |

 

## 使用方法

 

### 方式一：使用脚本（推荐）

 

```
node scripts/parse_ddl.js <sql文件路径> [输出文件路径]
```

 

示例：

 

```
node scripts/parse_ddl.js ddl.sql 表结构导出.xlsx
```

 

### 方式二：在代码中使用

 

```
const { parseCreateTables, generateExcel } = require('./scripts/parse_ddl');

const fs = require('fs');
const sqlContent = fs.readFileSync('ddl.sql', 'utf-8');

// 解析表结构
const tables = parseCreateTables(sqlContent);

// 生成 Excel
generateExcel(tables, 'output.xlsx');
```

 

## 支持的数据类型

 

脚本会自动识别以下 MySQL 数据类型并设置默认长度：

 

| 数据类型 | 默认长度 |
| --- | --- |
| tinyint | 3 |
| smallint | 5 |
| mediumint | 7 |
| int/integer | 10 |
| bigint | 19 |
| decimal/numeric | 38 |
| float | 12 |
| double | 22 |
| datetime/timestamp | 6 |
| date | 10 |
| time | 8 |
| year | 4 |
| boolean/bool | 1 |
| text/tinytext/mediumtext/longtext | 65535 |
| blob/tinyblob/mediumblob/longblob | 65535 |
| json | 1073741824 |
| varchar(n) | n |
| char(n) | n |

 

## 依赖

 

- Node.js &gt;= 14
- xlsx 包 (` npm install xlsx `)

 

## 安装依赖

 

```
cd scripts
npm install xlsx
```

 

## 注意事项

 

1. 脚本会跳过约束定义（PRIMARY KEY, INDEX, FOREIGN KEY 等）
2. Sheet 名称限制为 31 个字符（Excel 限制）
3. 如果表名超过 31 字符，会自动截断
4. 如果截断后有重名，会自动添加序号后缀

 

## 示例

 

输入 SQL：

 

```
CREATE TABLE users (
    id bigint NOT NULL AUTO_INCREMENT,
    username varchar(50) NOT NULL,
    email varchar(100) NULL,
    created_at timestamp(6) NULL,
    PRIMARY KEY (id)
);
```

 

输出 Excel：

 

|  | A | B | C | D |
| --- | --- | --- | --- | --- |
| 1 | 表名：users |  |  |  |
| 2 | 属性名 | 数据类型 | 长度 | 精度 |
| 3 | id | bigint | 19 | 0 |
| 4 | username | varchar | 50 | 0 |
| 5 | email | varchar | 100 | 0 |
| 6 | created\_at | timestamp | 6 | 0 |
