跳到主要内容

自定义页面表格导入导出

在ERP系统和人力资源管理系统中,我们经常遇到需要将产品信息、员工信息等数据从外部源批量导入到宜搭自定义页面的表格内,或是反过来,将这些自定义页面中的表格数据导出为Excel格式文件,以便进一步分析或与公司其他部门分享。下面,我们将通过具体示例来详细介绍如何实现这种数据的导入与导出功能。

前提条件

本教程使用到宜搭部分基础功能,你可以先了解以下功能。

本教程使用到三方资源,你可以了解以下功能。

实现效果

导入

导出

实现步骤

此例导入导出是基于前端方式实现的,目前暂不支持移动端使用。

创建自定义页面

页面内容区块如下。

完整配置源码

{
"schemaType": "superform",
"schemaVersion": "5.0",
"utils": [
{
"name": "legaoBuiltin",
"type": "npm",
"content": {
"package": "@ali/vu-legao-builtin",
"version": "3.0.0",
"exportName": "legaoBuiltin"
}
},
{
"name": "yidaPlugin",
"type": "npm",
"content": {
"package": "@ali/vu-yida-plugin",
"version": "1.1.0",
"exportName": "yidaPlugin"
}
}
],
"actions": {
"module": {
"compiled": "'use strict';\n\nexports.__esModule = true;\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nexports.didMount = didMount;\nexports.onSuccess = onSuccess;\nexports.readWorkbookFromRemoteFile = readWorkbookFromRemoteFile;\nexports.excelImportToTable = excelImportToTable;\nexports.onSelectChange = onSelectChange;\nexports.onExportData = onExportData;\n// 当页面渲染完毕后马上调用下面的函数,这个函数是在当前页面 - 设置 - 生命周期 - 页面加载完成时中被关联的。\nfunction didMount() {\n this.utils.loadScript('https://g.alicdn.com/code/lib/xlsx/0.18.5/xlsx.full.min.js');\n}\n\n// 上传成功\nfunction onSuccess(file, value) {\n if (value && value.length) {\n this.readWorkbookFromRemoteFile(file);\n }\n}\n\n// 从上传的文件中解析EXCEL内容并回调处理函数\nfunction readWorkbookFromRemoteFile(file) {\n var _this = this;\n\n var reader = new FileReader();\n reader.onload = function (e) {\n var workbook = XLSX.read(e.target.result, { type: 'arraybuffer' });\n _this.excelImportToTable(workbook);\n };\n reader.readAsArrayBuffer(file.originFileObj);\n}\n\n// 导入到表格处理\nfunction excelImportToTable(workbook) {\n var sheetNames = workbook.SheetNames; // 工作表名称集合\n var worksheet = workbook.Sheets[sheetNames[0]]; // 只读取第一张sheet\n var tableJson = XLSX.utils.sheet_to_json(worksheet);\n var data = tableJson.map(function (item, index) {\n return {\n text1: item['单行文本1'], // 表格对应组件标识:item[excel对应的列名称]\n text2: item['单行文本2'],\n text3: item['单行文本3'],\n id: index\n };\n });\n // 写入表格\n this.setState({\n tableData: {\n currentPage: 1,\n data: data,\n totalCount: data.length\n }\n });\n this.utils.toast({\n title: '数据导入完成',\n type: 'success'\n });\n}\n\n// 选择变动回调\nfunction onSelectChange(selectedRowKeys, records) {\n this.setState({\n records: records\n });\n}\n\n// 导出数据\nfunction onExportData() {\n var records = this.state.records;\n\n if (!records.length || !records) {\n this.utils.toast({\n title: '当前未选中任何数据',\n type: 'warning'\n });\n return;\n };\n // 导出 excel 列名称\n var sheetHeader = [{\n title: '单行文本1',\n value: 'text1'\n }, {\n title: '单行文本2',\n value: 'text2'\n }, {\n title: '单行文本3',\n value: 'text3'\n }];\n var result = [];\n for (var i = 0; i < records.length; i++) {\n var item = {};\n for (var j = 0; j < sheetHeader.length; j++) {\n item[sheetHeader[j].title] = records[i][sheetHeader[j].value];\n };\n result.push(item);\n }\n // 新建空workbook,然后加入worksheet\n var ws = XLSX.utils.json_to_sheet(result);\n // 设置每列的列宽,10代表10个字符,注意中文占2个字符\n ws['!cols'] = [{ wch: 10 }, { wch: 10 }, { wch: 10 }];\n // 新建book\n var wb = XLSX.utils.book_new();\n // 生成xlsx文件(book,sheet数据,sheet命名)\n XLSX.utils.book_append_sheet(wb, ws, 'sheet1');\n // 写文件\n var workbookBlob = workbook2blob(wb);\n openDownloadDialog(workbookBlob, this.utils.formatter('date', Date.now(), 'YYYYMMDDhhmmss') + '.xlsx');\n}\n\nfunction openDownloadDialog(blob, fileName) {\n if ((typeof blob === 'undefined' ? 'undefined' : _typeof(blob)) == 'object' && blob instanceof Blob) {\n blob = URL.createObjectURL(blob); // 创建blob地址\n }\n var aLink = document.createElement('a');\n aLink.href = blob;\n // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,有时候 file:///模式下不会生效\n aLink.download = fileName || '';\n var event;\n event = document.createEvent('MouseEvents');\n event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);\n aLink.dispatchEvent(event);\n}\n\n// 生成excel的配置项\nfunction workbook2blob(workbook) {\n var wbout = XLSX.write(workbook, {\n // 要生成的文件类型\n bookType: 'xlsx',\n bookSST: false,\n type: 'binary'\n });\n // 将字符串转ArrayBuffer\n function s2ab(s) {\n var buf = new ArrayBuffer(s.length);\n var view = new Uint8Array(buf);\n for (var i = 0; i != s.length; ++i) {\n view[i] = s.charCodeAt(i) & 0xff;\n }return buf;\n }\n var blob = new Blob([s2ab(wbout)], {\n type: 'application/octet-stream'\n });\n return blob;\n}\n",
"source": "// 当页面渲染完毕后马上调用下面的函数,这个函数是在当前页面 - 设置 - 生命周期 - 页面加载完成时中被关联的。\nexport function didMount() {\n this.utils.loadScript('https://g.alicdn.com/code/lib/xlsx/0.18.5/xlsx.full.min.js');\n}\n\n// 上传成功\nexport function onSuccess(file, value) {\n if (value && value.length) {\n this.readWorkbookFromRemoteFile(file);\n }\n}\n\n// 从上传的文件中解析EXCEL内容并回调处理函数\nexport function readWorkbookFromRemoteFile(file) {\n const reader = new FileReader();\n reader.onload = (e) => {\n let workbook = XLSX.read(e.target.result, { type: 'arraybuffer' });\n this.excelImportToTable(workbook);\n };\n reader.readAsArrayBuffer(file.originFileObj);\n}\n\n// 导入到表格处理\nexport function excelImportToTable(workbook) {\n let sheetNames = workbook.SheetNames; // 工作表名称集合\n let worksheet = workbook.Sheets[sheetNames[0]]; // 只读取第一张sheet\n let tableJson = XLSX.utils.sheet_to_json(worksheet);\n const data = tableJson.map((item, index) => {\n return {\n text1: item['单行文本1'], // 表格对应组件标识:item[excel对应的列名称]\n text2: item['单行文本2'],\n text3: item['单行文本3'],\n id: index\n };\n });\n // 写入表格\n this.setState({\n tableData: {\n currentPage: 1,\n data,\n totalCount: data.length,\n },\n })\n this.utils.toast({\n title: '数据导入完成',\n type: 'success'\n });\n}\n\n// 选择变动回调\nexport function onSelectChange(selectedRowKeys, records) {\n this.setState({\n records,\n });\n}\n\n// 导出数据\nexport function onExportData() {\n const { records } = this.state;\n if (!records.length || !records) {\n this.utils.toast({\n title: '当前未选中任何数据',\n type: 'warning'\n });\n return;\n };\n // 导出 excel 列名称\n const sheetHeader = [{\n title: '单行文本1',\n value: 'text1'\n }, {\n title: '单行文本2',\n value: 'text2'\n }, {\n title: '单行文本3',\n value: 'text3'\n }];\n const result = [];\n for (let i = 0; i < records.length; i++) {\n let item = {};\n for (let j = 0; j < sheetHeader.length; j++) {\n item[sheetHeader[j].title] = records[i][sheetHeader[j].value];\n };\n result.push(item);\n }\n // 新建空workbook,然后加入worksheet\n const ws = XLSX.utils.json_to_sheet(result);\n // 设置每列的列宽,10代表10个字符,注意中文占2个字符\n ws['!cols'] = [\n { wch: 10 },\n { wch: 10 },\n { wch: 10 }\n ];\n // 新建book\n const wb = XLSX.utils.book_new();\n // 生成xlsx文件(book,sheet数据,sheet命名)\n XLSX.utils.book_append_sheet(wb, ws, 'sheet1');\n // 写文件\n const workbookBlob = workbook2blob(wb);\n openDownloadDialog(workbookBlob, `${this.utils.formatter('date', Date.now(), 'YYYYMMDDhhmmss')}.xlsx`);\n}\n\nfunction openDownloadDialog(blob, fileName) {\n if (typeof blob == 'object' && blob instanceof Blob) {\n blob = URL.createObjectURL(blob); // 创建blob地址\n }\n var aLink = document.createElement('a');\n aLink.href = blob;\n // HTML5新增的属性,指定保存文件名,可以不要后缀,注意,有时候 file:///模式下不会生效\n aLink.download = fileName || '';\n var event;\n event = document.createEvent('MouseEvents');\n event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false,\n false, false, false, 0, null);\n aLink.dispatchEvent(event);\n}\n\n// 生成excel的配置项\nfunction workbook2blob(workbook) {\n var wbout = XLSX.write(workbook, {\n // 要生成的文件类型\n bookType: 'xlsx',\n bookSST: false,\n type: 'binary',\n });\n // 将字符串转ArrayBuffer\n function s2ab(s) {\n var buf = new ArrayBuffer(s.length);\n var view = new Uint8Array(buf);\n for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;\n return buf;\n }\n var blob = new Blob([s2ab(wbout)], {\n type: 'application/octet-stream',\n });\n return blob;\n}"
},
"type": "FUNCTION",
"list": [
{
"id": "didMount",
"title": "didMount"
},
{
"id": "onSuccess",
"title": "onSuccess"
},
{
"id": "readWorkbookFromRemoteFile",
"title": "readWorkbookFromRemoteFile"
},
{
"id": "excelImportToTable",
"title": "excelImportToTable"
},
{
"id": "onSelectChange",
"title": "onSelectChange"
},
{
"id": "onExportData",
"title": "onExportData"
}
]
},
"pages": [
{
"componentsTree": [
{
"componentName": "Page",
"id": "node_oclckak0691",
"props": {
"contentBgColor": "white",
"pageStyle": {
"backgroundColor": "#f2f3f5"
},
"contentMargin": "16",
"contentPadding": "24",
"showTitle": false,
"contentPaddingMobile": "0",
"templateVersion": "1.0.0",
"contentMarginMobile": "12",
"className": "page_lckamzub",
"contentBgColorMobile": "white"
},
"condition": true,
"css": "body{background-color:#f2f3f5}.richtext_lckamzuc {\n margin-bottom: 12px;\n}\n",
"methods": {
"__initMethods__": {
"type": "js",
"source": "function (exports, module) { /*set actions code here*/ }",
"compiled": "function (exports, module) { /*set actions code here*/ }"
}
},
"dataSource": {
"offline": [],
"globalConfig": {},
"online": [
{
"isReadonly": true,
"formUuid": "FORM-8D90776A119448178D63335FE3EC4940Z81V",
"name": "urlParams",
"description": "当前页面地址的参数:如 aliwork.com/APP_xxxx/workbench?id=1&name=宜搭,可通过 this.state.urlParams.name 获取到宜搭",
"id": "XHA66881GB57WESFEZE7A813VTG2390PLCKCLV",
"protocal": "URI"
},
{
"initialData": {
"variable": "{
\n currentPage: 1,
\n data: [
\n {
\n text1: 1,
\n text2: 'A',
\n text3: 'a',
\n id: 0
\n }, {
\n text1: 2,
\n text2: 'B',
\n text3: 'b',
\n id: 1
\n }, {
\n text1: 3,
\n text2: 'C',
\n text3: 'c',
\n id: 2
\n }, {
\n text1: 4,
\n text2: 'D',
\n text3: 'd',
\n id: 3
\n },
\n ],
\n totalCount: 4,
\n}",
"type": "variable",
"value": ""
},
"formUuid": "FORM-8D90776A119448178D63335FE3EC4940Z81V",
"isModified": false,
"name": "tableData",
"description": "表格数据",
"id": "IMD665A15D0RT22WCXS8L4L9W1ZI332UF3M4MR2",
"protocal": "VALUE"
},
{
"initialData": {
"variable": "[]",
"type": "variable",
"value": ""
},
"formUuid": "FORM-8D90776A119448178D63335FE3EC4940Z81V",
"isModified": true,
"name": "records",
"description": "当前选择的数据",
"id": "XHA66881GB57WESFEZE7A813VTG23E0PLCKCLW",
"protocal": "VALUE"
}
],
"list": [
{
"isReadonly": true,
"formUuid": "FORM-8D90776A119448178D63335FE3EC4940Z81V",
"name": "urlParams",
"description": "当前页面地址的参数:如 aliwork.com/APP_xxxx/workbench?id=1&name=宜搭,可通过 this.state.urlParams.name 获取到宜搭",
"id": "XHA66881GB57WESFEZE7A813VTG2390PLCKCLV",
"protocal": "URI"
},
{
"initialData": {
"variable": "{
\n currentPage: 1,
\n data: [
\n {
\n text1: 1,
\n text2: 'A',
\n text3: 'a',
\n id: 0
\n }, {
\n text1: 2,
\n text2: 'B',
\n text3: 'b',
\n id: 1
\n }, {
\n text1: 3,
\n text2: 'C',
\n text3: 'c',
\n id: 2
\n }, {
\n text1: 4,
\n text2: 'D',
\n text3: 'd',
\n id: 3
\n },
\n ],
\n totalCount: 4,
\n}",
"type": "variable",
"value": ""
},
"formUuid": "FORM-8D90776A119448178D63335FE3EC4940Z81V",
"isModified": false,
"name": "tableData",
"description": "表格数据",
"id": "IMD665A15D0RT22WCXS8L4L9W1ZI332UF3M4MR2",
"protocal": "VALUE"
},
{
"initialData": {
"variable": "[]",
"type": "variable",
"value": ""
},
"formUuid": "FORM-8D90776A119448178D63335FE3EC4940Z81V",
"isModified": true,
"name": "records",
"description": "当前选择的数据",
"id": "XHA66881GB57WESFEZE7A813VTG23E0PLCKCLW",
"protocal": "VALUE"
}
],
"sync": true
},
"lifeCycles": {
"constructor": {
"type": "js",
"compiled": "function constructor() {\nvar module = { exports: {} };\nvar _this = this;\nthis.__initMethods__(module.exports, module);\nObject.keys(module.exports).forEach(function(item) {\n if(typeof module.exports[item] === 'function'){\n _this[item] = module.exports[item];\n }\n});\n\n}",
"source": "function constructor() {\nvar module = { exports: {} };\nvar _this = this;\nthis.__initMethods__(module.exports, module);\nObject.keys(module.exports).forEach(function(item) {\n if(typeof module.exports[item] === 'function'){\n _this[item] = module.exports[item];\n }\n});\n\n}"
},
"componentWillUnmount": "",
"componentDidMount": {
"name": "didMount",
"id": "didMount",
"params": {},
"type": "actionRef"
}
},
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": "",
"children": [
{
"componentName": "RootHeader",
"id": "node_oclckak0692",
"props": {},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": ""
},
{
"componentName": "RootContent",
"id": "node_oclckak0693",
"props": {},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": "",
"children": [
{
"componentName": "AttachmentField",
"id": "node_oclckak0697",
"props": {
"labelTipsTypes": "none",
"__useMediator": "value",
"labelTipsIcon": "",
"__gridSpan": 1,
"linkage": "",
"type": "drag",
"listType": "text",
"buttonSize": "medium",
"tips": {
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"autoUpload": true,
"buttonType": "normal",
"valueType": "custom",
"limit": 1,
"labelTextAlign": "left",
"behavior": "NORMAL",
"value": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"validation": [],
"__style__": {},
"fieldId": "attachmentField_lbyiyc8g",
"buttonText": {
"type": "i18n",
"zh_CN": "上传文件",
"en_US": "Upload"
},
"method": "post",
"visibility": [
"PC",
"MOBILE"
],
"dataEntryMode": false,
"submittable": "DEFAULT",
"multiple": false,
"labelColOffset": 0,
"label": {
"type": "i18n",
"zh_CN": "上传导入数据",
"en_US": "Upload attachment"
},
"maxFileSize": 100,
"__category__": "form",
"labelColSpan": 4,
"wrapperColSpan": 0,
"onlineEdit": false,
"accept": ".xls,.xlsx",
"wrapperColOffset": 0,
"complexValue": {
"complexType": "custom",
"formula": "",
"value": {
"en_US": "",
"zh_CN": "",
"type": "i18n"
}
},
"size": "medium",
"labelAlign": "top",
"withCredentials": false,
"formula": "",
"labelTipsText": {
"type": "i18n",
"zh_CN": "",
"en_US": ""
},
"onSuccess": {
"type": "JSExpression",
"value": "this.utils.legaoBuiltin.execEventFlow.bind(this, [this.onSuccess])",
"events": [
{
"name": "onSuccess",
"id": "onSuccess",
"params": {},
"type": "actionRef",
"uuid": "1671690691449_0"
}
]
}
},
"condition": true,
"loopArgs": [
"",
""
],
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": ""
},
{
"componentName": "RichText",
"id": "node_oclckak0698",
"props": {
"foldHeight": 110,
"visibility": [
"PC",
"MOBILE"
],
"contentPaddingMobile": "16",
"isFold": false,
"isDefaultFold": false,
"className": "richtext_lckamzuc",
"behavior": "NORMAL",
"imagePreview": "NONE",
"content": {
"en_US": "rich text",
"zh_CN": "[\"root\",{},[\"p\",{},[\"span\",{\"data-type\":\"text\"},[\"span\",{\"data-type\":\"leaf\"},\"Excel 数据示例:\"]]]]",
"type": "i18n"
},
"__style__": ":root {\n margin-bottom: 12px;\n}\n",
"fieldId": "richText_lbyiyc8l",
"disableCopy": false
},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": ""
},
{
"componentName": "Image",
"id": "node_oclckak0699",
"props": {
"preview": false,
"autoHeight": false,
"visibility": [
"PC",
"MOBILE"
],
"src": "https://img.alicdn.com/imgextra/i3/O1CN016ayemJ24I8cQQtELy_!!6000000007367-0-tps-425-253.jpg",
"alt": "Image 404",
"fit": "cover",
"round": "0",
"width": "350",
"autoWidth": false,
"roundRadius": "0",
"__style__": {},
"height": "200",
"fieldId": "image_lbyprljo"
},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": ""
},
{
"componentName": "TablePc",
"id": "node_oclckak0696",
"props": {
"actionWidth": 0,
"rowSelection": {
"mode": "multiple",
"selectedRowKeys": "",
"onChange": {
"name": "onSelectChange",
"id": "onSelectChange",
"type": "actionRef",
"params": {}
}
},
"isTree": false,
"pagination": {
"paginationPosition": "right",
"size": "medium",
"type": "normal",
"shape": "arrow-only",
"pageSizeSelector": false,
"pageSizeList": [
5,
10,
20
],
"pageSize": 10,
"pageSizePosition": "end",
"pageShowCount": 5,
"hideOnlyOnePage": false,
"showJump": true,
"showMiniPager": false
},
"data": {
"type": "variable",
"value": {
"data": [],
"totalCount": 0
},
"variable": "state.tableData"
},
"actionTitle": {
"type": "i18n",
"zh_CN": "操作",
"en_US": "Action"
},
"indent": 16,
"columns": [
{
"enumData": [
{
"color": "blue",
"text": "正常",
"value": "1"
},
{
"color": "red",
"text": "异常",
"value": "-1"
},
{
"color": "grey",
"text": "未知",
"value": "0"
}
],
"hidden": false,
"resizable": false,
"dataType": "text",
"__sid": "item_lckakuig",
"sortable": false,
"filters": "",
"title": {
"use": "zh_CN",
"en_US": "Name",
"zh_CN": "单行文本1",
"type": "i18n"
},
"float": "",
"align": "left",
"message": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"enumBadgeType": "background",
"dataKey": "text1",
"highlight": false,
"filterMode": "multiple",
"groupName": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"editProps": {
"rules": [],
"placeholder": ""
},
"width": 200,
"editType": "text",
"lock": "none",
"timeFormatter": "YYYY-MM-DD HH:mm:ss"
},
{
"enumData": [
{
"color": "blue",
"text": "正常",
"value": "1"
},
{
"color": "red",
"text": "异常",
"value": "-1"
},
{
"color": "grey",
"text": "未知",
"value": "0"
}
],
"hidden": false,
"resizable": false,
"dataType": "text",
"__sid": "item_lckakuii",
"sortable": false,
"filters": "",
"title": {
"use": "zh_CN",
"en_US": "Name",
"zh_CN": "单行文本2",
"type": "i18n"
},
"float": "",
"align": "left",
"message": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"enumBadgeType": "background",
"dataKey": "text2",
"highlight": false,
"filterMode": "multiple",
"groupName": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"editProps": {
"rules": [],
"placeholder": ""
},
"width": 200,
"editType": "text",
"lock": "none",
"timeFormatter": "YYYY-MM-DD HH:mm:ss"
},
{
"enumData": [
{
"color": "blue",
"text": "正常",
"value": "1"
},
{
"color": "red",
"text": "异常",
"value": "-1"
},
{
"color": "grey",
"text": "未知",
"value": "0"
}
],
"hidden": false,
"resizable": false,
"dataType": "text",
"__sid": "item_lckakuik",
"sortable": false,
"filters": "",
"title": {
"use": "zh_CN",
"en_US": "Name",
"zh_CN": "单行文本3",
"type": "i18n"
},
"float": "",
"align": "left",
"message": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"enumBadgeType": "background",
"dataKey": "text3",
"highlight": false,
"filterMode": "multiple",
"groupName": {
"use": "zh_CN",
"en_US": "",
"zh_CN": "",
"type": "i18n"
},
"editProps": {
"rules": [],
"placeholder": ""
},
"width": 200,
"editType": "text",
"lock": "none",
"timeFormatter": "YYYY-MM-DD HH:mm:ss"
}
],
"mobileExpandViewMode": "normal",
"expandedRowIndent": "[]",
"showCustomColumn": false,
"setLoadingComponent": false,
"showRowSelector": true,
"showLinkBar": false,
"maxWebShownActionCount": 3,
"fixedHeader": false,
"hasExpandedRowCtrl": true,
"showActionBar": true,
"showSearch": false,
"stickyHeader": false,
"useStickyLock": false,
"theme": "split",
"expandedRowRender": "",
"setEmptyContent": false,
"actionFixed": "none",
"fieldId": "tablePc_lckakub0",
"isPagination": true,
"actionColumn": [
{
"title": {
"en_US": "Detail",
"use": "zh_CN",
"zh_CN": "详情",
"type": "i18n"
},
"option": "callback"
}
],
"openRowKeys": "",
"noPadding": true,
"hasHeader": true,
"useVirtual": false,
"getExpandedColProps": "function getExpandedColProps(record, index) { }",
"actionBar": [
{
"callback": {
"name": "onExportData",
"id": "onExportData",
"type": "actionRef",
"params": {}
},
"__sid": "item_lckakuio",
"title": {
"en_US": "Action 1",
"zh_CN": "导出选中数据",
"type": "i18n"
},
"option": "callback"
}
],
"loading": false,
"onRowOpen": "",
"actionType": "link",
"isExpand": false,
"mobileMargin": 0,
"__router": {
"type": "variable",
"value": {
"type": "JSExpression",
"value": "this.utils.router"
},
"variable": "this.utils.router"
},
"mobileMode": "normal",
"showCustomBarItem": false,
"actionHidden": true,
"dataSourceType": "data",
"primaryKey": "id"
},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": ""
}
]
},
{
"componentName": "RootFooter",
"id": "node_oclckak0694",
"props": {},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": "",
"children": [
{
"componentName": "FooterYida",
"id": "node_oclckak0695",
"props": {},
"condition": true,
"hidden": false,
"title": "",
"isLocked": false,
"conditionGroup": ""
}
]
}
]
}
],
"componentsMap": [
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "RootHeader"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "AttachmentField"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "RichText"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "Image"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "TablePc"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "RootContent"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "FooterYida"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "RootFooter"
},
{
"package": "@ali/vc-deep-yida",
"version": "1.5.169",
"componentName": "Page"
}
]
}
]
}

配置数据源变量

{
currentPage: 1,
data: [
{
text1: 1,
text2: 'A',
text3: 'a',
id: 0
}, {
text1: 2,
text2: 'B',
text3: 'b',
id: 1
}, {
text1: 3,
text2: 'C',
text3: 'c',
id: 2
}, {
text1: 4,
text2: 'D',
text3: 'd',
id: 3
},
],
totalCount: 4,
}

数据源变量绑定

表格组件绑定变量,设置数据主键

加载 xlsx.js

export function didMount() {
this.utils.loadScript('https://g.alicdn.com/code/lib/xlsx/0.18.5/xlsx.full.min.js');
}

导入

配置上传 Excel 导入至表格中

// 上传成功
export function onSuccess(file, value) {
if (value && value.length) {
this.readWorkbookFromRemoteFile(file);
}
}

// 从上传的文件中解析EXCEL内容并回调处理函数
export function readWorkbookFromRemoteFile(file) {
const reader = new FileReader();
reader.onload = (e) => {
let workbook = XLSX.read(e.target.result, { type: 'arraybuffer' });
this.excelImportToTable(workbook);
};
reader.readAsArrayBuffer(file.originFileObj);
}

// 导入到表格处理
export function excelImportToTable(workbook) {
let sheetNames = workbook.SheetNames; // 工作表名称集合
let worksheet = workbook.Sheets[sheetNames[0]]; // 只读取第一张sheet
let tableJson = XLSX.utils.sheet_to_json(worksheet);
const data = tableJson.map((item, index) => {
return {
text1: item['单行文本1'], // 表格对应组件标识:item[excel对应的列名称]
text2: item['单行文本2'],
text3: item['单行文本3'],
id: index
};
});
// 写入表格
this.setState({
tableData: {
currentPage: 1,
data,
totalCount: data.length,
},
})
this.utils.toast({
title: '数据导入完成',
type: 'success'
});
}

导出

配置表格选中数据导出至 Excel 中

// 选择变动回调
export function onSelectChange(selectedRowKeys, records) {
this.setState({
records,
});
}

// 导出数据
export function onExportData() {
const { records } = this.state;
if (!records.length || !records) {
this.utils.toast({
title: '当前未选中任何数据',
type: 'warning'
});
return;
};
// 导出 excel 列名称
const sheetHeader = [{
title: '单行文本1',
value: 'text1'
}, {
title: '单行文本2',
value: 'text2'
}, {
title: '单行文本3',
value: 'text3'
}];
const result = [];
for (let i = 0; i < records.length; i++) {
let item = {};
for (let j = 0; j < sheetHeader.length; j++) {
item[sheetHeader[j].title] = records[i][sheetHeader[j].value];
};
result.push(item);
}
// 新建空workbook,然后加入worksheet
const ws = XLSX.utils.json_to_sheet(result);
// 设置每列的列宽,10代表10个字符,注意中文占2个字符
ws['!cols'] = [
{ wch: 10 },
{ wch: 10 },
{ wch: 10 }
];
// 新建book
const wb = XLSX.utils.book_new();
// 生成xlsx文件(book,sheet数据,sheet命名)
XLSX.utils.book_append_sheet(wb, ws, 'sheet1');
// 写文件
const workbookBlob = workbook2blob(wb);
openDownloadDialog(workbookBlob, `${this.utils.formatter('date', Date.now(), 'YYYYMMDDhhmmss')}.xlsx`);
}

function openDownloadDialog(blob, fileName) {
if (typeof blob == 'object' && blob instanceof Blob) {
blob = URL.createObjectURL(blob); // 创建blob地址
}
var aLink = document.createElement('a');
aLink.href = blob;
// HTML5新增的属性,指定保存文件名,可以不要后缀,注意,有时候 file:///模式下不会生效
aLink.download = fileName || '';
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false,
false, false, false, 0, null);
aLink.dispatchEvent(event);
}

// 生成excel的配置项
function workbook2blob(workbook) {
var wbout = XLSX.write(workbook, {
// 要生成的文件类型
bookType: 'xlsx',
bookSST: false,
type: 'binary',
});
// 将字符串转ArrayBuffer
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
return buf;
}
var blob = new Blob([s2ab(wbout)], {
type: 'application/octet-stream',
});
return blob;
}

保存页面

在线试玩

Copyright © 2025钉钉(中国)信息技术有限公司和/或其关联公司浙ICP备18037475号-4