Excel 操作
安装
npm i -S x-excel-util
使用
import Vue from 'vue'
import xExcelUtil from 'x-excel-util'
Vue.use(xExcelUtil)
- Excel 导入(可单个引入)
<x-excel-import :columns="columns" :headerRow="true" @dataHandler="dataHandler">
导入
</x-excel-import>
- Excel 导出(可单个引入)
<x-excel-export
:data="data"
:columns="exportColumns"
:headerRow="true"
>
导出
</x-excel-export>
配置
- Excel 导入
参数 | 类型 | 说明 |
---|---|---|
columns | Object Array | 列定义 [可选] |
headerRow | Boolean | 是否包括标题行(读取时候跳过,默认true) |
sheetId | Number or String | 表索引 默认1 |
- Excel 导出
参数 | 类型 | 说明 |
---|---|---|
data | Object Array | 数据 |
filename | String | 保存的文件名称 (默认export.xlsx) |
creator | String | 创建人(默认system) |
sheetName | String | 表名称(默认 Sheet 1) |
columns | Object Array | 列定义 |
headerRow | Boolean | 是否包括标题行(默认true) |
事件
Excel读取回调函数
dataHandler
包含一个参数,参数为表格数据
-
指定columns
返回
[{key:value}]
形式 -
未指定columns
返回[[v1,v2,...]]形式
列定义
字段 | 类型 | 描述 |
---|---|---|
title | String | 列标题 |
key | String | 对应字段Key |
width | Number | 宽度,建议取10 |
value | Function | [可选] 数据格式化函数,输入为record[key] |
parse | Function | [可选] 数据解析函数 |
dataValidation | Object | 列数据验证 |
格式化和解析可用于复杂JSON的输出和读入
数据验证
详情请看 ExcelJS文档
单元格可以定义哪些值有效或无效,并提示用户以帮助指导它们。
验证类型可以是以下之一:
类型 | 描述 |
---|---|
list | 定义一组离散的有效值。Excel 将在下拉菜单中提供这些内容,以便于输入 |
whole | 该值必须是整数 |
decimal | 该值必须是十进制数 |
textLength | 该值可以是文本,但长度是受控的 |
custom | 自定义公式控制有效值 |
对于 list
或 custom
以外的其他类型,以下运算符会影响验证:
运算符 | 描述 |
---|---|
between | 值必须介于公式结果之间 |
notBetween | 值不能介于公式结果之间 |
equal | 值必须等于公式结果 |
notEqual | 值不能等于公式结果 |
greaterThan | 值必须大于公式结果 |
lessThan | 值必须小于公式结果 |
greaterThanOrEqual | 值必须大于或等于公式结果 |
lessThanOrEqual | 值必须小于或等于公式结果 |
// 指定有效值的列表(One,Two,Three,Four)。
// Excel 将提供一个包含这些值的下拉列表。
dataValidation = {
type: 'list',
allowBlank: true,
formulae: ['"One,Two,Three,Four"']
};
// 指定单元格必须为非5的整数。
// 向用户显示适当的错误消息(如果他们弄错了)
dataValidation = {
type: 'whole',
operator: 'notEqual',
showErrorMessage: true,
formulae: [5],
errorStyle: 'error',
errorTitle: 'Five',
error: 'The value must not be Five'
};
// 指定单元格必须为1.5到7之间的十进制数字。
// 添加“工具提示”以帮助指导用户
dataValidation = {
type: 'decimal',
operator: 'between',
allowBlank: true,
showInputMessage: true,
formulae: [1.5, 7],
promptTitle: 'Decimal',
prompt: 'The value must between 1.5 and 7'
};
// 指定单元格的文本长度必须小于15
dataValidation = {
type: 'textLength',
operator: 'lessThan',
showErrorMessage: true,
allowBlank: true,
formulae: [15]
};
// 指定单元格必须是2016年1月1日之前的日期
dataValidation = {
type: 'date',
operator: 'lessThan',
showErrorMessage: true,
allowBlank: true,
formulae: [new Date(2016,0,1)]
};