方式一:layui签到导入导出
layui第三方插件地址:https://fly.layui.com/jie/47273/ http://excel.wj2015.com/_book/
jsp页面:
jquery-1.11.3.min.js
layui.js
excel.js
<%--Created by IntelliJ IDEA.User: jiamingDate: 2019/12/31Time: 12:34To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>excel导入导出</title><!--先加载jquery--><script type="text/javascript" src="js/jquery-1.11.3.min.js"></script><script src="layui_new/layui/layui.js" charset="utf-8"></script><!--再加载插件--><script src="layui_exts/excel.js" charset="utf-8"></script><script type="text/javascript">$(function () {layui.config({base: 'layui_exts/'}).extend({excel: 'excel'});// LAY_EXCEL.exportExcel([[1, 2, 3]], '表格导出.xlsx', 'xlsx');layui.use(['jquery', 'excel', 'layer'], function () {var $ = layui.jquery;var excel = layui.excel;$.ajax({url: '/path/to/get/data',dataType: 'json',success: function (res) {// 假如返回的 res.data 是需要导出的列表数据console.log(res.data);// [{name: 'wang', age: 18, sex: '男'}, {name: 'layui', age: 3, sex: '女'}]// 1. 数组头部新增表头res.data.unshift({name: '用户名', sex: '男', age: '年龄'});// 2. 如果需要调整顺序,请执行梳理函数var data = excel.filterExportData(res.data, ['name','sex','age',]);// 3. 执行导出函数,系统会弹出弹框excel.exportExcel({sheet1: data}, '导出接口数据.xlsx', 'xlsx');}});// 监听上传文件的事件$('#LAY-excel-import-excel').change(function (e) {var files = e.target.files;try {// 方式一:先读取数据,后梳理数据excel.importExcel(files, {}, function (data) {console.log(data);data = excel.filterImportData(data, {'id': 'A', 'username': 'B', 'experience': 'C', 'sex': 'D', 'score': 'E', 'city': 'F', 'classify': 'G', 'wealth': 'H', 'sign': 'I'})console.log(data);});// 方式二:可以在读取过程中梳理数据excel.importExcel(files, {fields: {'id': 'A', 'username': 'B', 'experience': 'C', 'sex': 'D', 'score': 'E', 'city': 'F', 'classify': 'G', 'wealth': 'H', 'sign': 'I'}}, function (data) {console.log(data);});} catch (e) {layer.alert(e.message);}});});});</script></head><body><input type="file" class="layui-btn layui-btn-primary" id="LAY-excel-import-excel" multiple="multiple"></body></html>
方式二:poi后端导入,layui前端导出
**
前台jsp:
jquery-1.11.3.min.js
public.js
<%--Created by IntelliJ IDEA.User: jiamingDate: 2020/1/1Time: 12:05To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head><title>后台实现excel导入操作</title><script type="text/javascript" src="js/jquery-1.11.3.min.js"></script><script type="text/javascript" src="js/public.js"></script></head><body><script>function submit3() {// ajax里面将参数自动转换为json格式,所以后台接收必须用"@RequestBody"接收doUploadFile("TestExcel/addExcel","myForm", function (data) {console.log(data);});}</script><form id="myForm">请选择上传的excel文件:<input type="file" name="file">额外参数:<input type="text" name="name"><input type="button" value="提交" onclick="submit3();"></form></body></html>
后端java:
控制层
package jxxdxy.controller;import jxxdxy.model.Back;import jxxdxy.model.Result;import jxxdxy.model.TestFile;import jxxdxy.util.ExcelUtil;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.multipart.MultipartHttpServletRequest;import javax.servlet.http.HttpServletRequest;import java.io.InputStream;import java.util.List;@Controller@RequestMapping("TestExcel")public class TestExcel {@RequestMapping("addExcel")@ResponseBodypublic Back addFile(TestFile file, HttpServletRequest request){System.out.println("接收的对象:"+file);System.out.println(file.getFile().getOriginalFilename()+"--"+file.getFile().getSize());Back back = new Back();MultipartFile excl = file.getFile();if (request instanceof MultipartHttpServletRequest) {//说明文件不为空if (!excl.isEmpty()) {try {String fileName = excl.getOriginalFilename();//转化为流的形式InputStream is = excl.getInputStream();List<Row> list = ExcelUtil.getExcelRead(fileName, is, true);//首先是读取行 也就是一行一行读,然后在取到列,遍历行里面的行,根据行得到列的值for (Row row : list) {Cell cell_0 = row.getCell(0);System.out.println(ExcelUtil.getValue(cell_0));//得到每个元素的值start// Cell cell_0 = row.getCell(0);// Cell cell_1 = row.getCell(1);// Cell cell_2 = row.getCell(2);// Cell cell_3 = row.getCell(3);// Cell cell_4 = row.getCell(4);// //得到列的值,也就是你需要解析的字段的值// String name = ExcelUtil.getValue(cell_0);// String nickName = ExcelUtil.getValue(cell_1);// String phone = ExcelUtil.getValue(cell_2);// String actorName = ExcelUtil.getValue(cell_3);// String status = ExcelUtil.getValue(cell_4);// String regex = "^1[3|4|5|8][0-9]\\d{8}$";// if ("".equals(name)){// result.setSuccess(false);// result.setErrorMessage("第"+(row.getRowNum())+"行第"+1+"列的姓名不能为空!");// return result;// } else if (!(phone.matches(regex))){// result.setSuccess(false);// result.setErrorMessage("第"+(row.getRowNum())+"行第" +3+ "列的手机号码格式不正确");// return result;// } else if("".equals(actorName)){// result.setSuccess(false);// result.setErrorMessage("第"+(row.getRowNum())+"行第"+5+"列的角色名不能为空!");// return result;// } else if("".equals(status)) {// result.setSuccess(false);// result.setErrorMessage("第"+(row.getRowNum())+"行第" + 6 + "列的状态不能为空!");// return result;// }else if (!("启用".equals(status)) || ("禁用".equals(status))){// result.setSuccess(false);// result.setErrorMessage("第"+(row.getRowNum())+"行第" + 6 + "列的状态只能为启用或禁用");// return result;// }}System.out.println("预览成功");back.setCode(0);back.setMsg("表格数据预览");} catch (Exception e) {e.printStackTrace();System.out.println("预览出现异常");back.setCode(0);back.setMsg("预览失败,预览出现异常");}} else {System.out.println("预览失败,文件为空");back.setCode(0);back.setMsg("预览失败,文件为空");}}return back;}}
模型层
package jxxdxy.model;import org.springframework.web.multipart.MultipartFile;import java.util.Arrays;public class TestFile {private String name;//额外参数private MultipartFile file;//上传文件private MultipartFile[] files;//上传多个文件@Overridepublic String toString() {return "TestFile{" +"name='" + name + '\'' +", file=" + file +", files=" + Arrays.toString(files) +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public MultipartFile getFile() {return file;}public void setFile(MultipartFile file) {this.file = file;}public MultipartFile[] getFiles() {return files;}public void setFiles(MultipartFile[] files) {this.files = files;}}
帮助类
package jxxdxy.util;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.InputStream;import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;/*** @author huwei*/public class ExcelUtil {/*** 获取解析文件行数据* @param fileName : 文件地址* @param isTitle : 是否过滤第一行解析* @return* @throws Exception*/public static List<Row> getExcelRead(String fileName, InputStream is, boolean isTitle) throws Exception{try {//判断其兼容版本 调用了判断版本的方法Workbook workbook = getWorkbook(fileName,is);Sheet sheet = workbook.getSheetAt(0);int count = 0;List<Row> list = new ArrayList<Row>();for (Row row : sheet) {// 跳过第一行的目录if (count == 0 && isTitle) {count++;continue;}list.add(row);}return list;} catch (Exception e) {throw e;}}/**判断版本的方法*/public static Workbook getWorkbook(String fileName,InputStream is) throws Exception{Workbook workbook = null;try {/** 判断文件的类型,是2003还是2007 */boolean isExcel2003 = true;if (WDWUtil.isExcel2007(fileName)) {isExcel2003 = false;}if (isExcel2003) {workbook = new HSSFWorkbook(is);} else {workbook = new XSSFWorkbook(is);}} catch (Exception e) {throw e;}return workbook;}/**得到celL值的方法:*/public static String getValue(Cell cell){if (cell == null || cell.equals("")){return String.valueOf("");}else {switch (cell.getCellTypeEnum()) {case BOOLEAN:return String.valueOf(cell.getBooleanCellValue());case NUMERIC:double value = cell.getNumericCellValue();return new BigDecimal(value).toString();case STRING:return String.valueOf(cell.getStringCellValue());default:return String.valueOf(cell.getStringCellValue());}}}}
pom.xml文件
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.jxxdxy</groupId><artifactId>wlms</artifactId><version>1.0-SNAPSHOT</version><packaging>war</packaging><name>wlms Maven Webapp</name><!-- FIXME change it to the project's website --><url>http://www.example.com</url><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><maven.compiler.source>1.7</maven.compiler.source><maven.compiler.target>1.7</maven.compiler.target><spring-version>3.2.8.RELEASE</spring-version><jdbc.version>8.0.12</jdbc.version><log4j.version>2.7</log4j.version><slf4j.version>1.7.21</slf4j.version><httpasyncclient.version>4.1.2</httpasyncclient.version><jdk.version>1.7</jdk.version></properties><profiles><profile><id>maven2-release</id><distributionManagement><snapshotRepository><id>oss</id><url>https://oss.sonatype.org/content/repositories/snapshots/</url></snapshotRepository><repository><id>oss</id><url>https://oss.sonatype.org/service/local/staging/deploy/maven2/</url></repository></distributionManagement></profile></profiles><dependencies><!-- 短信发送--><dependency><groupId>com.yunpian.sdk</groupId><artifactId>yunpian-java-sdk</artifactId><version>1.2.7</version></dependency><!--支付宝--><dependency><groupId>com.alipay.sdk</groupId><artifactId>alipay-sdk-java</artifactId><version>3.7.4.ALL</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-simple</artifactId><version>${slf4j.version}</version><scope>test</scope></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-nop</artifactId><version>1.7.2</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.0</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpasyncclient</artifactId><version>${httpasyncclient.version}</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpasyncclient-cache</artifactId><version>${httpasyncclient.version}</version></dependency><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpmime</artifactId><version>4.5.2</version></dependency><!-- 连接池--><dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.8.8</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency><dependency><groupId>org.codehaus.xfire</groupId><artifactId>xfire-spring</artifactId><version>1.2.6</version><exclusions><exclusion><groupId>org.springframework</groupId><artifactId>spring</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.17</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.17</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.11</version><scope>test</scope></dependency><!--Spring配置--><dependency><groupId>commons-dbcp</groupId><artifactId>commons-dbcp</artifactId><version>1.4</version></dependency><dependency><groupId>commons-pool</groupId><artifactId>commons-pool</artifactId><version>1.6</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-tx</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jdbc</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>${spring-version}</version></dependency><!--事务--><dependency><groupId>org.springframework</groupId><artifactId>spring-aspects</artifactId><version>${spring-version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-jms</artifactId><version>${spring-version}</version></dependency><!-- mybatis核心包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.3.0</version></dependency><!-- mybatis/spring包 --><dependency><groupId>org.mybatis</groupId><artifactId>mybatis-spring</artifactId><version>1.2.2</version></dependency><!-- 数据库驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${jdbc.version}</version></dependency><!-- json包--><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.31</version></dependency><!-- log4j --><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>${log4j.version}</version></dependency><!--文件上传包 --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.2</version></dependency><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20160810</version></dependency></dependencies><build><!-- 短信发送--><resources><resource><directory>src/main/java</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory><includes><include>**/*.properties</include><include>**/*.xml</include></includes></resource></resources><plugins><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.6.0</version><configuration><source>${jdk.version}</source><target>${jdk.version}</target><encoding>${project.build.sourceEncoding}</encoding></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-resources-plugin</artifactId><version>3.0.1</version><executions><execution><phase>compile</phase></execution></executions><configuration><encoding>${project.build.sourceEncoding}</encoding></configuration></plugin><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>2.19.1</version><configuration><skip>true</skip></configuration></plugin><plugin><artifactId>maven-assembly-plugin</artifactId><executions><execution><phase>package</phase><goals><goal>single</goal></goals></execution></executions><configuration><descriptorRefs><descriptorRef>jar-with-dependencies</descriptorRef></descriptorRefs></configuration></plugin></plugins><!-- end--><finalName>wlms</finalName><pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) --><plugins><plugin><artifactId>maven-clean-plugin</artifactId><version>3.0.0</version></plugin><!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging --><plugin><artifactId>maven-resources-plugin</artifactId><version>3.0.2</version></plugin><plugin><artifactId>maven-compiler-plugin</artifactId><version>3.7.0</version></plugin><plugin><artifactId>maven-surefire-plugin</artifactId><version>2.20.1</version></plugin><plugin><artifactId>maven-war-plugin</artifactId><version>3.2.0</version></plugin><plugin><artifactId>maven-install-plugin</artifactId><version>2.5.2</version></plugin><plugin><artifactId>maven-deploy-plugin</artifactId><version>2.8.2</version></plugin></plugins></pluginManagement></build></project>
