> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# JSON 导出 Excel

## 业务场景

在开发后台管理系统过程中，大多会遇到以下场景：

- 将查询出来的 JSON 数据导出生成 Excel 类型的文件；
- 前端读取 Excel 类型文件，生成 JSON 数据；

读文件和写文件的场景在开发中非常常见，这里我们以导出 Excel xlsx 格式文件为例，介绍如何使用 JavaScript 读取当前的 JSON 数据，写入到 Excel xlsx 文件中。

## 安装依赖

```javascript title="代码示例"
yarn add write-excel-file
// or
npm install write-excel-file
// or
pnpm install write-excel-file
// or
bun install write-excel-file
```

:::tip 提示
具体操作方法请查看 npmjs [write-excel-file](https://www.npmjs.com/package/write-excel-file)；npmmirror 访问地址：[write-excel-file](https://npmmirror.com/package/write-excel-file)
:::

## 封装方法

```javascript title="代码示例"
import WriteXlsxFile from "write-excel-file";

/**
 * @description Json数据导出Xlsx
 * @param {Array} data JSON数据
 * @param {Array} header xlsx表头 [{key:'',name:'',width:''}]
 *  @param {String} key column的key
 *  @param {String} name column的name
 *  @param {Number} width column的width
 * @param {String} fileName xlsx文件名
 **/
export const DataToXlsx = async (data, header, fileName) => {
    let stmp = {
        column: "",
        with: 20,
        value: null,
    };

    let SCHEMA = header.map(({ key, name, width, type }) => {
        let column = Object.assign({}, stmp, {
            type: type ?? String,
            column: name,
            width: width || 20,
            value: (v) => v?.[key] ?? "",
        });
        return column;
    });

    let FILE_NAME =
        fileName.lastIndexOf(".xlsx") != -1 ? fileName : fileName + ".xlsx";

    await WriteXlsxFile(data, {
        schema: SCHEMA,
        fileName: FILE_NAME,
        headerStyle: {
            backgroundColor: "#f2f6fc",
            fontWeight: "bold",
            align: "center",
            height: 20,
        },
    });
};
```

:::danger 注意事项

- 依据 JSON 数据对应格式的文件类型配置对应 “key” 值的 “type” 属性；
- 借助第三方插件工具来实现数据格式的转换和导出；

:::
