search
HomeWeb Front-endLayui TutorialWhat 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
excellayuidocument

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/

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',
    });

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结束
});
//监听头工具栏事件结束

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);
		  }
	  });
}

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);
    }
}

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
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
How do I use Layui's flow module for infinite scrolling?How do I use Layui's flow module for infinite scrolling?Mar 18, 2025 pm 01:01 PM

The article discusses using Layui's flow module for infinite scrolling, covering setup, best practices, performance optimization, and customization for enhanced user experience.

How do I use Layui's element module to create tabs, accordions, and progress bars?How do I use Layui's element module to create tabs, accordions, and progress bars?Mar 18, 2025 pm 01:00 PM

The article details how to use Layui's element module to create and customize UI elements like tabs, accordions, and progress bars, highlighting HTML structures, initialization, and common pitfalls to avoid.Character count: 159

How do I customize the appearance and behavior of Layui's carousel module?How do I customize the appearance and behavior of Layui's carousel module?Mar 18, 2025 pm 12:59 PM

The article discusses customizing Layui's carousel module, focusing on CSS and JavaScript modifications for appearance and behavior, including transition effects, autoplay settings, and adding custom navigation controls.

How do I use Layui's carousel module to create image sliders?How do I use Layui's carousel module to create image sliders?Mar 18, 2025 pm 12:58 PM

The article guides on using Layui's carousel module for image sliders, detailing steps for setup, customization options, implementing autoplay and navigation, and performance optimization strategies.

How do I configure Layui's upload module to restrict file types and sizes?How do I configure Layui's upload module to restrict file types and sizes?Mar 18, 2025 pm 12:57 PM

The article discusses configuring Layui's upload module to restrict file types and sizes using accept, exts, and size properties, and customizing error messages for violations.

How do I use Layui's layer module to create modal windows and dialog boxes?How do I use Layui's layer module to create modal windows and dialog boxes?Mar 18, 2025 pm 12:46 PM

The article explains how to use Layui's layer module to create modal windows and dialog boxes, detailing setup, types, customization, and common pitfalls to avoid.

How does Layui compare to other CSS frameworks like Bootstrap and Semantic UI?How does Layui compare to other CSS frameworks like Bootstrap and Semantic UI?Mar 14, 2025 pm 07:29 PM

Layui, known for simplicity and performance, is compared with Bootstrap and Semantic UI on design, components, and integration ease. Layui excels in modularity and Chinese support.(159 characters)

What are some advanced use cases for Layui beyond typical web applications?What are some advanced use cases for Layui beyond typical web applications?Mar 14, 2025 pm 07:28 PM

Layui extends beyond basic web apps to SPAs, real-time dashboards, PWAs, and complex data visualization, enhancing enterprise-level user experiences with its modular design and rich UI components.(159 characters)

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function