如何优雅的用POI导入Excel文件

在企业级项目开发中,要经常涉及excel文件和程序之间导入导出的业务要求,那么今天来讲一讲excel文件导入的实现。java实现对excel的操作有很多种方式,例如EasyExcel等,今天我们使用的是POI技术实现excel文件的导入。

POI技术简介

1.POI概念

Apache POI 是用Java编写的免费开源的跨平台的Java API,Apache POI提供API给Java程序对Microsoft Office格式档案读和写的功能,其中使用最多的就是使用POI操作Excel文件。POI为“Poor Obfuscation Implementation”的首字母缩写,意为“简洁版的模糊实现”。

官网地址:

https://poi.apache.org/components/index.html

2.POI坐标依赖


<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>

3.POI核心API概述

3.1 创建工作簿对象

Workbook workbook=new XSSFWorkbook(path)

3.2 获取execl表中的sheet对象

Sheet sheet = workbook.getSheetAt(0);

3.3 获取excel文件中所有物理数据的有效行数

int rows = sheet.getPhysicalNumberOfRows()

3.4 获取行对象

Row row =sheet.getRow(i)

3.5 获取行中的列对象

Cell cell=row.getCell(0)

3.6 获取列的字符串类型数据

cell.getStringCellValue()

3.7 获取列的数字类型字段数据

cell.getNumericCellValue()

POI技术使用

1.需求分析

从一个准备好的Excel表格文件中读取学生信息,然后将学生的信息通过POI技术导入到数据库的学生表中。

2.实现思路

以下是具体的实现思路:

  • 准备excel文件,里面存储若干学生信息:包含学生姓名、年龄和手机号;

  • 创建web项目,导入相关jar依赖;

  • 创建数据库并创建一张学生表;

  • 使用POI读取文件的学生信息;

  • 将获取到的学生信息封装到学生对象;

  • 通过JDBC技术将学生信息保存到学生表。

3.案例实现

3.1 准备学生信息的excel文件

我们先创建一个student.xlsx文件

3.2 创建web项目,导入jar依赖

pom.xml核心依赖如下:

<!-- POI依赖坐标 -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.2</version>
</dependency>
<!-- servlet -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>4.0.1</version>
    <scope>provided</scope>
</dependency>
<!-- 数据库相关 -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.6</version>
</dependency>
<!--c3p0-->
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5</version>
</dependency>
<!-- dbutils -->
<dependency>
    <groupId>commons-dbutils</groupId>
    <artifactId>commons-dbutils</artifactId>
    <version>1.7</version>
</dependency>
</dependencies>

3.3 创建数据库并创建一张学生表

#创建学生数据库
CREATE DATABASE studb;
#创建学生表
CREATE TABLE `student` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `sname` VARCHAR(30) DEFAULT NULL,
  `age` INT(11) DEFAULT NULL,
  `phone` VARCHAR(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

3.4 创建Student实体类

package com.qf.pojo;

public class Student {
    private Integer id;
    private String sname;
    private Integer age;
    private String phone;

    public Student(String sname, Integer age, String phone) {
        this.sname = sname;
        this.age = age;
        this.phone = phone;
    }

    public Student(Integer id, String sname, Integer age, String phone) {
        this.id = id;
        this.sname = sname;
        this.age = age;
        this.phone = phone;
    }

    public Student() {
    }

    public Integer getId() {
        return id;
    }

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

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public Integer getAge() {
        return age;
    }

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

    public String getPhone() {
        return phone;
    }

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

    @Override
    public String toString() {
        return "Student{" +
            "id=" + id +
            ", sname='" + sname + '\'' +
            ", age=" + age +
            ", phone='" + phone + '\'' +
            '}';
    }
}

3.5 创建StudentServlet

@WebServlet("/student")
public class StudentServlet extends BaseServlet{

    private StudentService studentService=new StudentService();
    /*POI导入学生信息*/
    public void poiImport(HttpServletRequest request,
                          HttpServletResponse response){

        System.out.println("POI导入学生信息");
        String path="D:\\ssm\\students.xlsx";
        try {
            //创建工作表对象
            Workbook workbook=new XSSFWorkbook(path);
            //获取目标sheet
            Sheet sheet = workbook.getSheetAt(0);
            //获取sheet数据总行数
            int rows = sheet.getPhysicalNumberOfRows();
            //获取sheet中所有数据
            for (int i = 1; i < rows; i++) {
                //获取当前行对象
                Row row = sheet.getRow(i);
                String sname = row.getCell(0).getStringCellValue();//姓名
                double value = row.getCell(1).getNumericCellValue();//年龄
                Integer age = (int)value;
                double tel = row.getCell(2).getNumericCellValue();//手机号
                BigDecimal bigDecimal=new BigDecimal(tel);
                String phone = bigDecimal.toString();
                //将获取的数据封装到学生对象
                Student student=new Student(sname,age,phone);
                //将数据保存数据库表
                studentService.insertStudent(student);
            }
            System.out.println("POI导入学生信息完毕!");
            response.setContentType("text/html;charset=utf-8");
            response.getWriter().write("POI导入学生信息完毕!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

3.6 创建StudentService

public class StudentService {
    private StudentDao studentDao=new StudentDao();
    /*增加学生*/
    public int insertStudent(Student s){
      return   studentDao.addStudent(s);
    }
}

3.7 创建StudentDao

public class StudentDao extends BaseDao<Student> {
    /*增加学生*/
    public int addStudent(Student s){
        String sql="insert into `student` ( `sname`, `age`, `phone`) values (?,?,?)";
       return update(sql, s.getSname(), s.getAge(), s.getPhone());
    }
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>POI使用</title>
</head>
<body>
<h2>POI导入数据</h2>
<a href="student?key=poiImport">导入学生信息</a>
</body>
</html>

4.效果图示例

首页效果如下图:

导入成功提示:

导入成功后学生表:

至此,我们就实现了POI导入excel文件的操作,当然还有一些更复杂的操作在这里没有展开,例如导入excel中的部分行、部分列的数据,以及导出数据到excel等操作。

猜你喜欢

转载自blog.csdn.net/longz_org_cn/article/details/129624634
今日推荐