SpringBoot导入导出数据实现方法详解
作者:披着星光的鲸鱼 发布时间:2023-10-03 19:47:22
今天给大家带来的是一个 SpringBoot导入导出数据
首先我们先创建项目 注意:创建SpringBoot项目时一定要联网不然会报错
项目创建好后我们首先对 application.yml 进行编译
server:
port: 8081
# mysql
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/dvd?characterEncoding=utf-8&&severTimezone=utc
username: root
password: root
thymeleaf:
mode: HTML5
cache: false
suffix: .html
prefix: classpath:/
mybatis:
mapperLocations: classpath:mapper/**/*.xml
configuration:
map-underscore-to-camel-case: true
pagehelper:
helper-dialect: mysql
offset-as-page-num: true
params: count=countSql
reasonable: true
row-bounds-with-count: true
support-methods-arguments: true
注意:在 :后一定要空格,这是他的语法,不空格就会运行报错
接下来我们进行对项目的构建 创建好如下几个包 可根据自己实际需要创建其他的工具包之类的
mapper:用于存放dao层接口
pojo:用于存放实体类
service:用于存放service层接口,以及service层实现类
controller:用于存放controller控制层
接下来我们开始编写代码
首先是实体类
package com.bdqn.springbootexcel.pojo;
import lombok.Data;
import java.io.Serializable;
import java.util.List;
@Data
public class ExcelData implements Serializable{
//文件名称
private String fileName;
//表头数据
private String[] head;
//数据
private List<String[]> data;
}
然后是service层
package com.bdqn.springbootexcel.service;
import com.bdqn.springbootexcel.pojo.User;
import org.apache.ibatis.annotations.Select;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
public interface ExcelService {
Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize);
Boolean importExcel(String fileName);
List<User> find();
}
package com.bdqn.springbootexcel.service;
import com.bdqn.springbootexcel.mapper.UserMapper;
import com.bdqn.springbootexcel.pojo.ExcelData;
import com.bdqn.springbootexcel.pojo.User;
import com.bdqn.springbootexcel.util.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
@Slf4j
@Service
public class ExcelServiceImpl implements ExcelService {
@Autowired
private UserMapper userMapper;
@Override
public Boolean exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize) {
log.info("导出数据开始。。。。。。");
//查询数据并赋值给ExcelData
List<User> userList = userMapper.find();
List<String[]> list = new ArrayList<String[]>();
for (User user : userList) {
String[] arrs = new String[userList.size()];
arrs[0] = String.valueOf(user.getId());
arrs[1] = String.valueOf(user.getName());
arrs[2] = String.valueOf(user.getAge());
arrs[3] = String.valueOf(user.getSex());
list.add(arrs);
}
//表头赋值
String[] head = {"序列", "名字", "年龄", "性别"};
ExcelData data = new ExcelData();
data.setHead(head);
data.setData(list);
data.setFileName(fileName);
//实现导出
try {
ExcelUtil.exportExcel(response, data);
log.info("导出数据结束。。。。。。");
return true;
} catch (Exception e) {
log.info("导出数据失败。。。。。。");
return false;
}
}
@Override
public Boolean importExcel(String fileName) {
log.info("导入数据开始。。。。。。");
try {
List<Object[]> list = ExcelUtil.importExcel(fileName);
System.out.println(list.toString());
for (int i = 0; i < list.size(); i++) {
User user = new User();
user.setName((String) list.get(i)[0]);
user.setAge((String) list.get(i)[1]);
user.setSex((String) list.get(i)[2]);
userMapper.add(user);
}
log.info("导入数据结束。。。。。。");
return true;
} catch (Exception e) {
log.info("导入数据失败。。。。。。");
e.printStackTrace();
}
return false;
}
@Override
public List<User> find() {
return userMapper.find();
}
}
工具类
package com.bdqn.springbootexcel.util;
import com.bdqn.springbootexcel.pojo.ExcelData;
import com.bdqn.springbootexcel.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import static org.apache.poi.ss.usermodel.CellType.*;
@Slf4j
public class ExcelUtil {
public static void exportExcel(HttpServletResponse response, ExcelData data) {
log.info("导出解析开始,fileName:{}",data.getFileName());
try {
//实例化HSSFWorkbook
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个Excel表单,参数为sheet的名字
HSSFSheet sheet = workbook.createSheet("sheet");
//设置表头
setTitle(workbook, sheet, data.getHead());
//设置单元格并赋值
setData(sheet, data.getData());
//设置浏览器下载
setBrowser(response, workbook, data.getFileName());
log.info("导出解析成功!");
} catch (Exception e) {
log.info("导出解析失败!");
e.printStackTrace();
}
}
private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
try {
HSSFRow row = sheet.createRow(0);
//设置列宽,setColumnWidth的第二个参数要乘以256,这个参数的单位是1/256个字符宽度
for (int i = 0; i <= str.length; i++) {
sheet.setColumnWidth(i, 15 * 256);
}
//设置为居中加粗,格式化时间格式
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//创建表头名称
HSSFCell cell;
for (int j = 0; j < str.length; j++) {
cell = row.createCell(j);
cell.setCellValue(str[j]);
cell.setCellStyle(style);
}
} catch (Exception e) {
log.info("导出时设置表头失败!");
e.printStackTrace();
}
}
private static void setData(HSSFSheet sheet, List<String[]> data) {
try{
int rowNum = 1;
for (int i = 0; i < data.size(); i++) {
HSSFRow row = sheet.createRow(rowNum);
for (int j = 0; j < data.get(i).length; j++) {
row.createCell(j).setCellValue(data.get(i)[j]);
}
rowNum++;
}
log.info("表格赋值成功!");
}catch (Exception e){
log.info("表格赋值失败!");
e.printStackTrace();
}
}
private static void setBrowser(HttpServletResponse response, HSSFWorkbook workbook, String fileName) {
try {
//清空response
response.reset();
//设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
//将excel写入到输出流中
workbook.write(os);
os.flush();
os.close();
log.info("设置浏览器下载成功!");
} catch (Exception e) {
log.info("设置浏览器下载失败!");
e.printStackTrace();
}
}
public static List<Object[]> importExcel(String fileName) {
log.info("导入解析开始,fileName:{}",fileName);
try {
List<Object[]> list = new ArrayList<>();
InputStream inputStream = new FileInputStream(fileName);
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
//获取sheet的行数
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
//过滤表头行
if (i == 0) {
continue;
}
//获取当前行的数据
Row row = sheet.getRow(i);
Object[] objects = new Object[row.getPhysicalNumberOfCells()];
int index = 0;
for (Cell cell : row) {
if (cell.getCellType().equals(NUMERIC)) {
objects[index] = (int) cell.getNumericCellValue();
}
if (cell.getCellType().equals(STRING)) {
objects[index] = cell.getStringCellValue();
}
if (cell.getCellType().equals(BOOLEAN)) {
objects[index] = cell.getBooleanCellValue();
}
if (cell.getCellType().equals(ERROR)) {
objects[index] = cell.getErrorCellValue();
}
index++;
}
list.add(objects);
}
log.info("导入文件解析成功!");
return list;
}catch (Exception e){
log.info("导入文件解析失败!");
e.printStackTrace();
}
return null;
}
//测试导入
public static void main(String[] args) {
try {
String fileName = "G:/test.xlsx";
List<Object[]> list = importExcel(fileName);
for (int i = 0; i < list.size(); i++) {
User user = new User();
user.setName((String) list.get(i)[0]);
user.setAge((String) list.get(i)[1]);
user.setSex((String) list.get(i)[2]);
System.out.println(user.toString());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
最后是controller层
package com.bdqn.springbootexcel.controller;
import com.bdqn.springbootexcel.pojo.User;
import com.bdqn.springbootexcel.service.ExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
@Slf4j
@RestController
public class ExcelController {
@Autowired
private ExcelService excelService;
@GetMapping("/export")
public String exportExcel(HttpServletResponse response, String fileName, Integer pageNum, Integer pageSize) {
fileName = "test.xlsx";
if (fileName == null || "".equals(fileName)) {
return "文件名不能为空!";
} else {
if (fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
Boolean isOk = excelService.exportExcel(response, fileName, 1, 10);
if (isOk) {
return "导出成功!";
} else {
return "导出失败!";
}
}
return "文件格式有误!";
}
}
@GetMapping("/import")
public String importExcel(String fileName) {
fileName = "G:/test.xlsx";
if (fileName == null && "".equals(fileName)) {
return "文件名不能为空!";
} else {
if (fileName.endsWith("xls") || fileName.endsWith("xlsx")) {
Boolean isOk = excelService.importExcel(fileName);
if (isOk) {
return "导入成功!";
} else {
return "导入失败!";
}
}
return "文件格式错误!";
}
}
//饼状图的数据查询
//@ResponseBody
@RequestMapping("/pojos_bing")
public List<User> gotoIndex() {
List<User> pojos = excelService.find();
return pojos;
}
}
到现在为止我们的后端代码就已经完全搞定了,前端页面如下
写了一个简单前端用于测试
index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div align="center">
<a th:href="@{'/export'}" rel="external nofollow" >导出</a>
<a th:href="@{'/import'}" rel="external nofollow" >导入</a>
</div>
</body>
</html>
当我们点击导出按钮时浏览器会自动下载
当我们点击导入按钮时会往数据库中添加表格数据
来源:https://blog.csdn.net/qq_45506892/article/details/128101466


猜你喜欢
- 今天在接手别人的一个项目的时候遇到一个坑,坑死我了;是一个打包的问题,好不容易我把代码写完了准备打包测试了,结果java -jar xxx.
- 本文为大家分享了C#基于Socket套接字的网络通信封装代码,供大家参考,具体内容如下摘要之所以要进行Socket套接字通信库封装,主要是直
- 提几个问题,从问题中去了解去学习:他们之间有啥区别?如果我使用notify(),将通知哪个线程?我怎么知道有多少线程在等待,所以我可以使用n
- onclick事件的定义方法,分为三种,分别为在xml中进行指定方法;在Actitivy中new出一个OnClickListenner();
- 数据结构是数据存储的方式,算法是数据计算的方式。所以在开发中,算法和数据结构息息相关。今天的讲义中会涉及部分数据结构的专业名词,如果各位铁粉
- 背景系统: SpringBoot开发的Web应用;ORM: JPA(Hibernate)接口功能简述: 根据实体类ID到数据库中查询实体信息
- 先看效果图:(以公司附近的国贸为中心点)上面是地图,下面是地理位置列表,有的只有地理位置列表(QQ动态的位置),这是个很常见的功能。它有个专
- 一、基本使用1、准备工程和引入控件1、下载、安装FastReport这一步很简单,大家在其中文网站上下载最新版的demo版就可以了,直接安装
- 前言已经有两个月没有更新博客了,其实这篇文章我早在两个月前就写好了,一直保存在草稿箱里没有发布出来。原因是有一些原理性的东西还没了解清楚,最
- 本文实例为大家分享了java实现2048小游戏的具体代码,供大家参考,具体内容如下效果图:游戏介绍:1.2048是一款益智类小游戏,刚开始随
- 1.分支结构的概念当需要进行条件判断并做出选择时,使用分支结构2.if分支结构格式:if(条件表达式){语句块;}package com.l
- JSON数据格式简洁,用于数据的持久化和对象传输很实用。最近在做一个Razor代码生成器,需要把数据库的表和列的信息修改后保存下来,想到用J
- Java异常层次结构Exception异常RuntimeException与非RuntimeException异常的区别:非RuntimeE
- Android 回调前言:Android中的回调最经典的就是点击事件设置监听(一般通过switch(v.getId()))这里写
- 前言日常开发中常见的文件格式有pdf,word,Excel,PPT,Html,txt,图片等。pdf,Html,txt,图片这种实现在线预览
- 大家都知道使用java反射可以在运行时动态改变对象的行为,甚至是private final的成员变量,但并不是所有情况下,都可以修改成员变量
- 大数据量操作的场景大致如下:数据迁移数据导出批量处理数据在实际工作中当指定查询数据过大时,我们一般使用分页查询的方式一页一页的将数据放到内存
- 一、简介:介绍两种使用 BitmapTransformation 来实现 Glide 加载圆形图片和圆角图片的方法。Glide 并不能直接支
- 背景后台系统需要接入 企业微信登入,满足企业员工快速登入系统流程图简单代码说明自定义一套 springsecurity 认证逻辑主要就是 根
- 在 Eclipse 里新建好工程后,默认会有一个assets目录,在 Eclipse 中直接将准备好的 SQLite 数据库复制到该目录中,