版权声明:有问题欢迎留言,转载请声明出处 https://blog.csdn.net/larger5/article/details/79329829
一、前言
最近涉及的项目如学生宿舍管理系统、题库、图片文字读取等,数据的导入导出,基本都是要用到 客户 熟悉的 Excel 表
下面来个 Excel导入导出 简单的使用记录,使用的基础知识:
① Excel 表格数据的处理,使用了 POl
② Java 后台,依旧是的简洁有力的 SpringBoot ,用 SSM+Maven 也基本一样
二、代码与结构
1、代码结构
代码修改之前文 使用 SpringBoot 写 Restful风格 增删改查接口
就增加了两个 controller 层中的 Excel 数据导入导出 接口
2、代码文件
① index.html 操作模拟模拟界面
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Excel表格数据导入导出</title>
</head>
<body>
<!-- Excel表格导出 -->
<a href="http://localhost/student/findall">导出Excel表格内容</a>
<hr>
<!-- Excel表格导入 -->
<form action="http://localhost/student/addall" method="post" enctype="multipart/form-data">
上传Excel数据文件<input type="file" name=fileupload>
<input type="submit" value="submit">
</form>
</body>
</html>
②、Student.java 实体
package com.cun.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
@Entity // 实体
@Table(name = "t_student") // 数据库表名
public class Student {
@Id // 主键
@GeneratedValue // 自增
private Integer id;
@NotEmpty(message = "学生姓名不能为空") // 表单验证
@Column(length = 20) // 字段长度
private String t_name;
@Column(length = 20) // 字段长度
private String major;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getT_name() {
return t_name;
}
public void setT_name(String t_name) {
this.t_name = t_name;
}
public String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
}
③ dao接口 StudentDao.java
package com.cun.dao;
import org.springframework.data.jpa.repository.JpaRepository;
import com.cun.entity.Student;
/**
* 简单的dao层只需要继承JpaRepository接口,即可,
* 复杂sql语句再自己增加接口
* @author linhongcun
*
*/
public interface StudentDao extends JpaRepository<Student, Integer>{
}
④ 事务层接口 StudentService.java
package com.cun.service;
import java.util.List;
import com.cun.entity.Student;
public interface StudentService {
public void addStudent(Student student);
public List<Student> findAllStudent();
}
⑤ 事务层实现类 StudentServiceImpl.java
package com.cun.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cun.dao.StudentDao;
import com.cun.entity.Student;
import com.cun.service.StudentService;
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
@Override
public void addStudent(Student student) {
// TODO Auto-generated method stub
studentDao.save(student);
}
@Override
public List<Student> findAllStudent() {
// TODO Auto-generated method stub
return studentDao.findAll();
}
}
⑥控制层 ,操作 Excel ,StudentController.java
package com.cun.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.cun.entity.Student;
import com.cun.service.StudentService;
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentservice;
/**
* 通过请求下载Excel表格数据
*
* @param response
* @throws IOException
*/
@RequestMapping(value = "/findall")
public void findAllStudent(HttpServletResponse response) throws IOException {
Workbook wb = new HSSFWorkbook();
String headers[] = { "id", "major", "t_name" };
int rowIndex = 0;
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(rowIndex++);
for (int i = 0; i < headers.length; i++) { // 先写表头
row.createCell(i).setCellValue(headers[i]);
}
List<Student> list = studentservice.findAllStudent();
for (int i = 0; i < list.size(); i++) {
row = sheet.createRow(rowIndex++);
row.createCell(0).setCellValue(list.get(i).getId());
row.createCell(1).setCellValue(list.get(i).getMajor());
row.createCell(2).setCellValue(list.get(i).getT_name());
}
response.setHeader("Content-Disposition",
"attachment;filename=" + new String("手动导出excel.xls".getBytes("utf-8"), "iso8859-1"));
response.setContentType("application/ynd.ms-excel;charset=UTF-8");
OutputStream out = response.getOutputStream();
wb.write(out);
out.flush();
out.close();
}
/**
* 必须先把文件写到本地,才能读取上传的文件的内容,因为File要用到路径,上传是没有路径的,只有文件
*
* @param fileupload
* @param request
* @throws IOException
*/
@PostMapping("/addall")
public void addAllSetudent(@RequestParam("fileupload")MultipartFile fileupload, HttpServletRequest request)
throws IOException {
String originalFilename = fileupload.getOriginalFilename();
String mypath = "C:\\LLLLLLLLLLLLLLLLLLL\\"+originalFilename;
//上传到本地
fileupload.transferTo(new File(mypath));
//Excel读取
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(mypath));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet hssfSheet = wb.getSheetAt(0); // 获取第一个Sheet页
if (hssfSheet != null) {
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
//mysql写入
Student student = new Student();
student.setId((int) hssfRow.getCell(0).getNumericCellValue());
student.setMajor(hssfRow.getCell(1).getStringCellValue());
student.setT_name(hssfRow.getCell(2).getStringCellValue());
studentservice.addStudent(student);
}
}
}
}
}
⑦ application.yml 配置文件
server:
port: 80 #为了以后访问项目不用写端口号
context-path: / #为了以后访问项目不用写项目名
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/webapp
username: root
password: 123
jpa:
hibernate:
ddl-auto: update #数据同步代码
show-sql: true #数据库操作时,显示sql语句
⑧ Maven 依赖 pom.xml,这里列出自己添加进去的,不含 Spring Tools 自动加入
<!-- POI -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<!-- JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQl -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
三、操作界面
1、主界面
2、点击链接,导出MySQL Excel 数据
3、点击 submit 选择合适的 Excel 文件导入数据进 MySQl 中
四、小结
1、里边的 Excel 表格的数据导入导出是写死的,
而实际应用,是先让客户导入 Excel 模板,再使用模板进行数据的导入导出,
不过道理差不多。