0.0.1 • Published 5 months ago

@yangchanghao/xlsx-transformer v0.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
5 months ago

@yangchanghao/xlsx-transformer

基于sheetJs封装,实现 json 数组和 excel 表格的相互转换以及上传下载功能

1.下载

(1)npm 方式下载:

npm install @yangchanghao/xlsx-transformer -S

(2)yarn 方式下载:

yarn add @yangchanghao/xlsx-transformer

2.如何使用

提示若出现 typescript 报错 @yangchanghao/xlsx-transformer 模块找不到,可以在声明文件 .d.ts 中添加如下代码

declare module '@yangchanghao/xlsx-transformer'

1.excel 表格转换成 json 数组

import { uploadFile, excel2Json } from '@yangchanghao/xlsx-transformer'
import type { IDicts } from '@yangchanghao/xlsx-transformer'

/** 数据翻译字典 */
const excelDicts: Array<IDicts> = [
  { label: 'name', value: '姓名' },
  { label: 'student_no', value: '学号' },
  { label: 'id', value: '序号' },
  { label: 'total_words', value: '总字数' },
  { label: 'true_percent', value: '正确率' },
  { label: 'time', value: '用时' },
]

/** 上传文件 */
uploadFile().then((file: Blob) => {
  /** 如果配置了dicts,那么就会根据excelDicts反向把表格里的汉字转换成英文,不配置则什么都不做 */
  excel2Json(file, { dicts: excelDicts })
    .then((res) => {
      console.log('JOSN数组是', res)
    })
    .catch((err) => console.log(err))
})

2.根据 json 数组生成 excel 表格并下载

import { donwLoadFile, json2Excel } from '@yangchanghao/xlsx-transformer'

const resultList: Array<Record<string, any>> = [
  { name: '学生1', student_no: 20147477, id: 1, total_words: 100, true_percent: 0.92, time: 3 },
  { name: '学生2', student_no: 20147472, id: 2, total_words: 100, true_percent: 0.92, time: 3 },
  { name: '学生3', student_no: 20147475, id: 3, total_words: 100, true_percent: 0.92, time: 3 },
  { name: '学生4', student_no: 20147471, id: 5, total_words: 100, true_percent: 0.92, time: 3 },
  { name: '学生5', student_no: 20147470, id: 4, total_words: 100, true_percent: 0.92, time: 3 },
]

/** 根据json数组和翻译字典数组生成excel表格文件 */
/** 如果配置了dicts,那么就会根据excelDicts把表格里的英文转换成汉字,不配置则什么都不做 */
json2Excel(resultList, { dicts: excelDicts }).then((res) => {
  /** 下载excel表格,并设置表格文件名称 */
  donwLoadFile(res, '学生成绩表')
})
0.0.1

5 months ago