Home Web Front-end Layui Tutorial What is the method for importing excel files in layui?

What is the method for importing excel files in layui?

Dec 07, 2020 pm 03:29 PM
excel layui document

What is the method for importing excel files in layui?

Let’s take a look at the completed renderings first:

(Related recommendations: layui)

What is the method for importing excel files in layui?

The specific steps are as follows:

First: Import the layui third-party plug-in js, address:

https://fly.layui.com/extend/excel/
Copy after login

1. Introduce the excel.js file into the page:

What is the method for importing excel files in layui?

//引入excel
    layui.config({
        base: 'layui_ext/',
    }).extend({
        excel: 'excel',
    });
Copy after login

2. Monitor the click event of the header toolbar

// 监听头工具栏事件
table.on('toolbar(terminalConfig)', function(obj) {
	var layer = layui.layer;
	// 添加终端
	if(obj.event == 'import'){
		layer.open({
			type : 1,
			shade : false,
			area : [ '350px', '260px' ],
			title : '导入Excel',
			content : $("#ImportExcel"),
			cancel : function() {
					layer.close();
			},
			success : function(layero, index) {
					ImportExcel();
			},
		});
						
	}
//导入Excel结束
});
//监听头工具栏事件结束
Copy after login

3. ImportExcel() method:

//导入方法
function ImportExcel(){
	var $ = layui.jquery
	  ,upload = layui.upload;
	  var uploadInst = upload.render({
		  elem: '#importExcel',
		  /*method: 'POST',*/
		  url: basePath + 'PowerUser/importPowerUserData.action',
		  accept: 'file', //普通文件
		  exts: 'xls|excel|xlsx', //导入表格
		  auto: false,  //选择文件后不自动上传
		  before: function (obj) {
			  layer.load(); //上传loading
		  },
		  choose: function (obj) {// 选择文件回调
			  var files = obj.pushFile();
			  var fileArr = Object.values(files);// 注意这里的数据需要是数组,所以需要转换一下
			  //console.debug(fileArr)
			  // 用完就清理掉,避免多次选中相同文件时出现问题
			  for (var index in files) {
				  if (files.hasOwnProperty(index)) {
					  delete files[index];
				  }
			  }
			  uploadExcel(fileArr); // 如果只需要最新选择的文件,可以这样写: uploadExcel([files.pop()])
		  },
		  error : function(){
			  setTimeout(function () {
				  layer.msg("上传失败!", {
						icon : 1
				});
				//关闭所有弹出层
				layer.closeAll(); //疯狂模式,关闭所有层
			  },1000);
		  }
	  });
}
Copy after login

4. uploadExcel() method:

function uploadExcel(files) {
    try {
    	var excel = layui.excel;
        excel.importExcel(files, {
            // 读取数据的同时梳理数据
            fields: {
            	'tId' : 'A',
				'inport' : 'B',
				'state' : 'C',
				'householdNumber' : 'D',
				'accountName' : 'E',
				'phone' : 'F'
            }
        }, function (data) {
            var arr = new Array();
            for(i = 1; i < data[0].Sheet1.length; i++){
            	var tt = {
                    	cId : selectConcentrator,
                    	tId : data[0].Sheet1[i].tId,
                    	inport: data[0].Sheet1[i].inport,
                    	state: data[0].Sheet1[i].state,
                    	householdNumber: data[0].Sheet1[i].householdNumber,
                    	accountName: data[0].Sheet1[i].accountName,
                    	phone: data[0].Sheet1[i].phone,
                    };
            	arr.push(tt);
            }
            
            $.ajax({
                async: false,
                url: basePath + &#39;PowerUser/importPowerUserData.action&#39;,
                type: &#39;post&#39;,
                dataType: "json",
                contentType: "application/x-www-form-urlencoded",
                data: {
                	data : JSON.stringify(arr)
                },
                success: function (data) {
                	if(data.success){
                		layer.msg(data.message);
                		setTimeout(function () {
                			layer.closeAll(); //疯狂模式,关闭所有层
                		},1000);
                		//表格导入成功后,重载表格
                		tableIns.reload(&#39;testTerminalConfigReload&#39;,{
                             url : basePath + &#39;PowerUser/PowerUserDataTable.action&#39;,
                             page : {
     							limit : 10, // 初始 每页几条数据
     							limits : [ 10, 20, 30 ]
     						// 可以选择的 每页几条数据
     						},
     						where : {
     							cId : selectConcentrator,
     							tId : selectTerminal
     						},
     						parseData: function(res){ //res 即为原始返回的数据
     						    return {
     						      "code": 0, //解析接口状态
     						      "msg": res.message, //解析提示文本
     						      "count": res.total, //解析数据长度
     						      "data": res.data //解析数据列表
     						    };
     						}
                         }, &#39;data&#39;);
                	}else{
                		//表格导入失败后,重载文件上传
                		layer.alert(data.error+"请重新上传",{icon : 2});
                	}
                },
                error: function (msg) {
                    layer.msg(&#39;请联系管理员!!!&#39;);
                }
            });
        });
    } catch (e) {
        layer.alert(e.message);
    }
}
Copy after login

Method 4 is to read the data and sort out the data. Parse the Excel data and then transfer the data to the backend. The backend parses the data and then inserts it into the database. After success, "Excel import successful" is returned to the front end. After the Excel import is successful, reload the table and the data can be displayed in the table.

The above is the detailed content of What is the method for importing excel files in layui?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to insert excel icons into PPT slides How to insert excel icons into PPT slides Mar 26, 2024 pm 05:40 PM

1. Open the PPT and turn the page to the page where you need to insert the excel icon. Click the Insert tab. 2. Click [Object]. 3. The following dialog box will pop up. 4. Click [Create from file] and click [Browse]. 5. Select the excel table to be inserted. 6. Click OK and the following page will pop up. 7. Check [Show as icon]. 8. Click OK.

How to set up jump on layui login page How to set up jump on layui login page Apr 04, 2024 am 03:12 AM

Layui login page jump setting steps: Add jump code: Add judgment in the login form submit button click event, and jump to the specified page through window.location.href after successful login. Modify the form configuration: add a hidden input field to the form element of lay-filter="login", with the name "redirect" and the value being the target page address.

How to read excel data in html How to read excel data in html Mar 27, 2024 pm 05:11 PM

How to read excel data in html: 1. Use JavaScript library to read Excel data; 2. Use server-side programming language to read Excel data.

How to get form data in layui How to get form data in layui Apr 04, 2024 am 03:39 AM

layui provides a variety of methods for obtaining form data, including directly obtaining all field data of the form, obtaining the value of a single form element, using the formAPI.getVal() method to obtain the specified field value, serializing the form data and using it as an AJAX request parameter, and listening Form submission event gets data.

Detailed method of inserting Excel circular data chart into PPT Detailed method of inserting Excel circular data chart into PPT Mar 26, 2024 pm 04:26 PM

1. Create a new PPT page and insert the Excel ring chart. 2. Delete the redundant data in the table, leaving two rows of data, and set them in percentage form to facilitate parameter setting. 3. Copy the data in column B to other columns according to display needs. From the sample picture of this column, you can see what it looks like when copying 5 columns. Pay attention to why the animation operation does not use dragging cells to copy, but the honest and practical method of copying and pasting. You will experience it when you actually operate it. 4. After copying N pieces, set the orange part to no color, and you are done. Note: 1. Use PPT to make information charts like this, which can be drawn graphically or accurately produced using Excel data. 2. This technique is valid for Excel 2007 and above.

Get data from Excel via HTML: A comprehensive guide Get data from Excel via HTML: A comprehensive guide Apr 09, 2024 am 10:03 AM

How to get Excel data in HTML? Import Excel files: using elements. Parse Excel files: use xlsx library or browser functionality. Get data: Get the worksheet object, including row and column data. Display data: Use HTML elements (such as tables) to display data.

Complete collection of excel function formulas Complete collection of excel function formulas May 07, 2024 pm 12:04 PM

1. The SUM function is used to sum the numbers in a column or a group of cells, for example: =SUM(A1:J10). 2. The AVERAGE function is used to calculate the average of the numbers in a column or a group of cells, for example: =AVERAGE(A1:A10). 3. COUNT function, used to count the number of numbers or text in a column or a group of cells, for example: =COUNT(A1:A10) 4. IF function, used to make logical judgments based on specified conditions and return the corresponding result.

How layui implements self-adaptation How layui implements self-adaptation Apr 26, 2024 am 03:00 AM

Adaptive layout can be achieved by using the responsive layout function of the layui framework. The steps include: referencing the layui framework. Define an adaptive layout container and set the layui-container class. Use responsive breakpoints (xs/sm/md/lg) to hide elements under specific breakpoints. Specify element width using the grid system (layui-col-). Create spacing via offset (layui-offset-). Use responsive utilities (layui-invisible/show/block/inline) to control the visibility of elements and how they appear.

See all articles