Java+JS实现导出网页数据到Excel表格

目录

 

剧情背景

一、创建数据库表and插入测试数据

二、创建后端环境及数据接口

1、创建POJO实体类——Student

2、创建数据层接口——StudentDao

3、创建数据库映射文件——StudentMapper

4、创建服务层接口——StudentService

5、创建服务层组件——StudentServiceImpl

6、创建后端控制器——StudentController

7、撸一个前端页面

 总结


剧情背景

最近博主接到老大安排的一个需求,在系统的Web页面查看订单的时候,可将订单批量导出至用户本地,以表格的方式呈现。

这个需求本来前端就可以纯JS实现,或者通过其他前端组件,奈何前端人员太菜,不知所云……所以博主就广集天下贤士的才智,最终采集到了一段相关的JS代码,又结合我写好的后端接口,返回过来JSON数组之后一顿操作……

话不多说,进入正题!按照以下流程跟我走,可以从0开始完成整个过程,全透明。

一、创建数据库表and插入测试数据

新建学生表:

CREATE TABLE `student` (
  `id` int(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(4) DEFAULT NULL,
  `phone` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

然后插入5条测试数据:

INSERT INTO student(`name`,age,phone)
VALUES('小王',23,'13256353663'),
('小张',19,'18956875328'),
('小李',18,'13569823262'),
('小方',21,'15686523156'),
('小赵',16,'18256353668');

二、创建后端环境及数据接口

这里采用SSM作为后端开发环境,需要用到的依赖包除基本的SSM所需的之外,还需要有阿里巴巴的fastJson,具体的Spring配置文件、MyBatis配置文件、web.xml这里就不列举了,相信各位搭建环境还是没问题的,这里只贴出来pom.xml,然后就直接从三层架构下手了。

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.lianqiao.dache</groupId>
  <artifactId>manager</artifactId>
  <version>1.0</version>
  <packaging>war</packaging>

  <name>money 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>
  </properties>

  <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>

  <dependencies>
    <dependency>
      <groupId>javax.annotation</groupId>
      <artifactId>javax.annotation-api</artifactId>
      <version>1.3.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/taglibs/standard -->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!--Spring模块-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context-support -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>5.1.1.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-core -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-expression -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-instrument -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-instrument</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-messaging -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-messaging</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-test -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>5.1.3.RELEASE</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.1.3.RELEASE</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/aopalliance/aopalliance -->
    <dependency>
      <groupId>aopalliance</groupId>
      <artifactId>aopalliance</artifactId>
      <version>1.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.aspectj/aspectjweaver -->
    <dependency>
      <groupId>org.aspectj</groupId>
      <artifactId>aspectjweaver</artifactId>
      <version>1.9.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>


    <!--文件模块-->
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.6</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-lang3</artifactId>
      <version>3.8.1</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.3</version>
    </dependency>




    <!--MyBatis与Spring模块-->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.2</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>2.6.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-dbcp2</artifactId>
      <version>2.5.0</version>
    </dependency>

    <!--MyBatis模块-->
    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.6</version>
    </dependency>

    <!--数据库模块-->
    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.13</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.47</version>
    </dependency>

  </dependencies>
</project>

1、创建POJO实体类——Student

package com.lianqiao.dache.entity;

/** 学生对象实体类
 * @author 秋枫艳梦
 * @date 2019-04-09
 * */
public class Student {
    //学生编号
    private int id;
    //学生姓名
    private String name;
    //学生年龄
    private int age;
    //学生手机
    private String phone;

    /**=============分割线,以下是getter、setter方法============*/

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }
}

2、创建数据层接口——StudentDao

package com.lianqiao.dache.dao;

import com.lianqiao.dache.entity.Student;

import java.util.List;

/** 学生信息数据层接口
 * @author 秋枫艳梦
 * @date 2019-04-09
 * */
public interface StudentDao {
    //获取学生列表
    List<Student> getStudentList();
}

3、创建数据库映射文件——StudentMapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lianqiao.dache.dao.StudentDao">
    <!--注意:不要盲目复制粘贴,注意你的Student和StudentDao接口的路径-->
    <select id="getStudentList" resultType="Student">
        select * from student
    </select>
</mapper>

4、创建服务层接口——StudentService

package com.lianqiao.dache.service;

import com.lianqiao.dache.entity.Student;

import java.util.List;

/** 学生信息服务层接口
 * @author 秋枫艳梦
 * @date 2019-04-09
 * */
public interface StudentService {
    //获取学生列表
    List<Student> getStudentList();
}

5、创建服务层组件——StudentServiceImpl

package com.lianqiao.dache.service.impl;

import com.lianqiao.dache.dao.StudentDao;
import com.lianqiao.dache.entity.Student;
import com.lianqiao.dache.service.StudentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/** 学生信息服务层组件
 * @author 秋枫艳梦
 * @date 2019-04-09
 * */
@Service("studentService")
public class StudentServiceImpl implements StudentService {

    //装配数据层组件
    @Resource(name = "studentDao")
    private StudentDao studentDao;

    /** 获取学生列表
     * @return Student集合
     * */
    @Override
    public List<Student> getStudentList() {
        return studentDao.getStudentList();
    }
}

6、创建后端控制器——StudentController

package com.lianqiao.dache.controller;

import com.alibaba.fastjson.JSON;
import com.lianqiao.dache.service.StudentService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;

/** 学生信息模块后端控制器
 * @author 秋枫艳梦
 * @date 2019-04-09
 * */
@Controller
public class StudentController {
    //装配业务层组件
    @Resource(name = "studentService")
    private StudentService studentService;

    /** 学生列表数据接口
     * @return JSON字符串
     * */
    @RequestMapping(value = "/student/info/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public Object getStudentList(){
        return JSON.toJSON(studentService.getStudentList());
    }
    
    /** 跳转到主页面
     * @return 视图名称
     * */
    @RequestMapping(value = "student.html")
    public String goPage(){
        return "student";
    }
}

7、撸一个前端页面

<!DOCTYPE html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>导出学生信息</title>
    <script type="text/javascript" src="/statics/js/jquery-3.2.1.min.js"></script>
    <script>
        window.onload=function () {
            getInfo();
        }
        /**
         *  发送Ajax请求,绑定表格数据
         * */
        function getInfo() {
            $.ajax({
                url:"/student/info/list",
                dataType:"json",
                success:function (dataJSON) {
                    var str="";
                    for (var i = 0; i < dataJSON.length; i++) {
                        str+="<tr>\n" +
                            "<td>"+dataJSON[i].id+"</td>\n" +
                            "<td>"+dataJSON[i].name+"</td>\n" +
                            "<td>"+dataJSON[i].age+"</td>\n" +
                            "<td>"+dataJSON[i].phone+"</td>\n" +
                            "</tr>";
                    }
                    $("#studentInfo").html(str);
                }
            });
        }

        /**
         *  导出数据
         * */
        function outData() {
            $.ajax({
                url:"/student/info/list",
                dataType:"json",
                success:function (dataJSON) {
                    //列标题,逗号隔开,每一个逗号就是隔开一个单元格
                    var str = "学生编号,学生姓名,学生年龄,学生电话\n";
                    
                    //遍历JSON数组,拼接Excel表格的每一行记录
                    for (var i = 0; i < dataJSON.length; i++) {
                        str+=dataJSON[i].id+"\t,"+dataJSON[i].name+"\t,"+dataJSON[i].age+"\t,"+dataJSON[i].phone+"\t,\n";
                    }
                    //解决中文乱码
                    var uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
                    //通过a标签实现
                    var link = document.createElement("a");
                    link.href = uri;
                    //对文件命名,后缀为csv、xls、xlsx都行
                    link.download =  "学生列表.csv";
                    document.body.appendChild(link);
                    link.click();
                    document.body.removeChild(link);
                }
            });
        }
    </script>
</head>
<body>
<a href="javascript:;" onclick="outData()">导出数据</a>
<table>
    <thead>
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>手机</th>
        </tr>
    </thead>
    <tbody id="studentInfo">

    </tbody>
</table>
</body>
</html>

然后启动项目,访问localhost:8080/student.html,就可以看到如下页面了,再点击导出,就提示下载CSV文件了。

然后打开下载下来的文件,是不是跟我们页面上的效果一样呢?

 总结

细心的朋友可以发现,其实页面上的表格跟导出的那一段JS代码,没有半毛钱的关系,我导出的时候仍然是走了一次Ajax请求,拿到数据之后再拼接文件的内容。

其实这一点可以通过纯前端JS实现,大不了就通过jQuery选择器获取页面中表格里的值呗,只不过我不喜欢那样,前端又菜鸡不会通过纯JS导出,所以我一个Java后端只能这样实现了……

还有一点,好多人问我可不可以设置下载路径,大家也看到了这是Web端的产品,我们只能做到向浏览器发起一个下载文件的请求,具体下载到哪还是根据浏览器的设置来的……

重点还是那一段JS,大家一定要举一反三,根据业务设置表头,拿到数据之后拼接文件内容就行了。

猜你喜欢

转载自blog.csdn.net/wzy18210825916/article/details/89152472
今日推荐