1.10.1 • Published 12 months ago

@ttou/midway-excel v1.10.1

Weekly downloads
-
License
MulanPSL2
Repository
-
Last release
12 months ago

Midway Excel

基于 exceljs 封装的组件,支持处理导入和导出表格。

相关信息:

描述
可用于标准项目
可用于 Serverless
可用于一体化

安装依赖

npm i @ttou/midway-excel class-transformer exceljs

或者在 package.json 中增加如下依赖后,重新安装。

{
  "dependencies": {
    "@ttou/midway-excel": "^1.0.0",
    "class-transformer": "^0.5.1",
    "exceljs": "^4.3.0"
    // ...
  }
}

开启组件

在 configuration.ts 中增加组件。

import { Configuration } from '@midwayjs/core';
import * as excel from '@ttou/midway-excel';

@Configuration({
  imports: [
    // ...
    excel
  ]
})
export class MainConfiguration {}

基础配置

然后在配置中设置,默认导出文件名为 文件

// src/config/config.default.ts
export default {
  // ...
  excel: {
    fileName: '文件',
  },
};

使用示例

// 定义序列化类 user-export.serialize.ts
import { Excel } from '@ttou/midway-excel'
import { Exclude } from 'class-transformer'

export class UserExportSerialize {
  @Excel({ header: '用户ID', width: 10 })
  userId: number

  @Excel({ header: '用户账号', width: 20 })
  userName: string

  @Exclude()
  password: string

  @Excel({ header: '备注', width: 20 })
  remark: string

  constructor(partial: any) {
    Object.assign(this, partial)
  }
}

export class UserTemplateSerialize {
  @Excel({ header: '用户ID', width: 10 })
  userId: number

  @Excel({ header: '用户账号', width: 20 })
  userName: string

  @Excel({ header: '用户密码', width: 20 })
  password: string

  @Excel({ header: '备注', width: 20 })
  remark: string
}
import { Controller, Inject, Post } from '@midwayjs/core'
import { Context } from '@midwayjs/koa'
import { ExcelService } from '@ttou/midway-excel'

import { UserExportSerialize, UserTemplateSerialize } from './user.serialize'

@Controller('/user')
export class UserController {
  @Inject()
  ctx: Context

  @Inject()
  excelService: ExcelService

  @Post('/template')
  async template() {
    const result = await this.excelService.handleTemplate({
      sheetName: 'User',
      fileName: '用户模板',
      Cls: UserTemplateSerialize,
    })

    this.ctx.set(result.headers)
    this.ctx.body = result.body
  }

  @Post('/import')
  async import(@File() file) {
    const result = await this.excelService.handleImport({
      sheetName: 'User',
      filePath: file.data,
      Cls: UserTemplateSerialize,
    })

    return result
  }

  @Post('/export')
  async export() {
    const data = [
      { userId: 1, userName: 'admin', password: '111111', remark: '用户备注' }
    ]

    const result = await this.excelService.handleExport({
      sheetName: 'User',
      fileName: '用户列表',
      Cls: UserExportSerialize,
      data
    })

    this.ctx.set(result.headers)
    this.ctx.body = result.body
  }
}
1.10.1

12 months ago

1.10.0

12 months ago

1.0.9

1 year ago

1.0.8

1 year ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago