SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)實現(xiàn)方法詳解
今天給大家?guī)淼氖且粋€ SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)
首先我們先創(chuàng)建項目 注意:創(chuàng)建SpringBoot項目時一定要聯(lián)網(wǎng)不然會報錯

項目創(chuàng)建好后我們首先對 application.yml 進(jìn)行編譯

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
注意:在 :后一定要空格,這是他的語法,不空格就會運行報錯
接下來我們進(jìn)行對項目的構(gòu)建 創(chuàng)建好如下幾個包 可根據(jù)自己實際需要創(chuàng)建其他的工具包之類的

mapper:用于存放dao層接口
pojo:用于存放實體類
service:用于存放service層接口,以及service層實現(xiàn)類
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;
//表頭數(shù)據(jù)
private String[] head;
//數(shù)據(jù)
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("導(dǎo)出數(shù)據(jù)開始。。。。。。");
//查詢數(shù)據(jù)并賦值給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);
//實現(xiàn)導(dǎo)出
try {
ExcelUtil.exportExcel(response, data);
log.info("導(dǎo)出數(shù)據(jù)結(jié)束。。。。。。");
return true;
} catch (Exception e) {
log.info("導(dǎo)出數(shù)據(jù)失敗。。。。。。");
return false;
}
}
@Override
public Boolean importExcel(String fileName) {
log.info("導(dǎo)入數(shù)據(jù)開始。。。。。。");
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("導(dǎo)入數(shù)據(jù)結(jié)束。。。。。。");
return true;
} catch (Exception e) {
log.info("導(dǎo)入數(shù)據(jù)失敗。。。。。。");
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("導(dǎo)出解析開始,fileName:{}",data.getFileName());
try {
//實例化HSSFWorkbook
HSSFWorkbook workbook = new HSSFWorkbook();
//創(chuàng)建一個Excel表單,參數(shù)為sheet的名字
HSSFSheet sheet = workbook.createSheet("sheet");
//設(shè)置表頭
setTitle(workbook, sheet, data.getHead());
//設(shè)置單元格并賦值
setData(sheet, data.getData());
//設(shè)置瀏覽器下載
setBrowser(response, workbook, data.getFileName());
log.info("導(dǎo)出解析成功!");
} catch (Exception e) {
log.info("導(dǎo)出解析失敗!");
e.printStackTrace();
}
}
private static void setTitle(HSSFWorkbook workbook, HSSFSheet sheet, String[] str) {
try {
HSSFRow row = sheet.createRow(0);
//設(shè)置列寬,setColumnWidth的第二個參數(shù)要乘以256,這個參數(shù)的單位是1/256個字符寬度
for (int i = 0; i <= str.length; i++) {
sheet.setColumnWidth(i, 15 * 256);
}
//設(shè)置為居中加粗,格式化時間格式
HSSFCellStyle style = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setBold(true);
style.setFont(font);
style.setDataFormat(HSSFDataFormat.getBuiltinFormat("m/d/yy h:mm"));
//創(chuàng)建表頭名稱
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("導(dǎo)出時設(shè)置表頭失??!");
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();
//設(shè)置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("設(shè)置瀏覽器下載成功!");
} catch (Exception e) {
log.info("設(shè)置瀏覽器下載失??!");
e.printStackTrace();
}
}
public static List<Object[]> importExcel(String fileName) {
log.info("導(dǎo)入解析開始,fileName:{}",fileName);
try {
List<Object[]> list = new ArrayList<>();
InputStream inputStream = new FileInputStream(fileName);
Workbook workbook = WorkbookFactory.create(inputStream);
Sheet sheet = workbook.getSheetAt(0);
//獲取sheet的行數(shù)
int rows = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < rows; i++) {
//過濾表頭行
if (i == 0) {
continue;
}
//獲取當(dāng)前行的數(shù)據(jù)
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("導(dǎo)入文件解析成功!");
return list;
}catch (Exception e){
log.info("導(dǎo)入文件解析失?。?);
e.printStackTrace();
}
return null;
}
//測試導(dǎo)入
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 "導(dǎo)出成功!";
} else {
return "導(dǎo)出失??!";
}
}
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 "導(dǎo)入成功!";
} else {
return "導(dǎo)入失??!";
}
}
return "文件格式錯誤!";
}
}
//餅狀圖的數(shù)據(jù)查詢
//@ResponseBody
@RequestMapping("/pojos_bing")
public List<User> gotoIndex() {
List<User> pojos = excelService.find();
return pojos;
}
}到現(xiàn)在為止我們的后端代碼就已經(jīng)完全搞定了,前端頁面如下
寫了一個簡單前端用于測試
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" >導(dǎo)出</a>
<a th:href="@{'/import'}" rel="external nofollow" >導(dǎo)入</a>
</div>
</body>
</html>當(dāng)我們點擊導(dǎo)出按鈕時瀏覽器會自動下載
當(dāng)我們點擊導(dǎo)入按鈕時會往數(shù)據(jù)庫中添加表格數(shù)據(jù)
到此這篇關(guān)于SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)實現(xiàn)方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot導(dǎo)入導(dǎo)出數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot內(nèi)存數(shù)據(jù)導(dǎo)出成Excel的實現(xiàn)方法
- 使用VUE+SpringBoot+EasyExcel?整合導(dǎo)入導(dǎo)出數(shù)據(jù)的教程詳解
- SpringBoot整合EasyExcel實現(xiàn)導(dǎo)入導(dǎo)出數(shù)據(jù)
- SpringBoot+easypoi實現(xiàn)數(shù)據(jù)的Excel導(dǎo)出
- SpringBoot 導(dǎo)出數(shù)據(jù)生成excel文件返回方式
- springboot 使用poi進(jìn)行數(shù)據(jù)的導(dǎo)出過程詳解
- Springboot與vue實現(xiàn)數(shù)據(jù)導(dǎo)出方法具體介紹
相關(guān)文章
SpringBoot+mail 輕松實現(xiàn)各類郵件自動推送
在實際的項目開發(fā)過程中,經(jīng)常需要用到郵件通知功能,例如,通過郵箱注冊,郵箱找回密碼,郵箱推送報表等等,實際的應(yīng)用場景非常的多,今天通過這篇文章,我們一起來學(xué)習(xí)如何在 Spring Boot 中快速實現(xiàn)一個自動發(fā)送郵件的功能2024-07-07
idea雙擊圖標(biāo)打不開,無反應(yīng)的解決
這篇文章主要介紹了idea雙擊圖標(biāo)打不開,無反應(yīng)的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-09-09
mybatis查詢數(shù)據(jù)賦值到model里面為空的解決
這篇文章主要介紹了mybatis查詢數(shù)據(jù)賦值到model里面為空的解決,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01
Spring Data JPA 建立表的聯(lián)合主鍵
這篇文章主要介紹了Spring Data JPA 建立表的聯(lián)合主鍵。本文詳細(xì)的介紹了2種方式,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04
Java實現(xiàn)把窗體隱藏到系統(tǒng)托盤方法
這篇文章主要介紹了Java實現(xiàn)把窗體隱藏到系統(tǒng)托盤方法,本文直接給出核心功能代碼,需要的朋友可以參考下2015-05-05

