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

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

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();
//創(chuàng)建一個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"));
//創(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("導出時設置表頭失??!");
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>當我們點擊導出按鈕時瀏覽器會自動下載
當我們點擊導入按鈕時會往數據庫中添加表格數據
到此這篇關于SpringBoot導入導出數據實現方法詳解的文章就介紹到這了,更多相關SpringBoot導入導出數據內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
spring?NamedContextFactory在Fegin配置及使用詳解
在我們日常項目中,使用FeignClient實現各系統(tǒng)接口調用變得更加簡單,?在各個系統(tǒng)集成過程中,難免會遇到某些系統(tǒng)的Client需要特殊的配置、返回讀取等需求。Feign使用NamedContextFactory來為每個Client模塊構造單獨的上下文(ApplicationContext)2023-11-11
Springboot jar運行時如何將jar內的文件拷貝到文件系統(tǒng)中
因為執(zhí)行需要,需要把jar內templates文件夾下的的文件夾及文件加壓到宿主機器的某個路徑下,以便執(zhí)行對應的腳本文件,這篇文章主要介紹了Springboot jar運行時如何將jar內的文件拷貝到文件系統(tǒng)中,需要的朋友可以參考下2024-06-06
springboot static關鍵字真能提高Bean的優(yōu)先級(厲害了)
這篇文章主要介紹了springboot static關鍵字真能提高Bean的優(yōu)先級(厲害了),需要的朋友可以參考下2020-07-07
Spring Boot啟動過程(五)之Springboot內嵌Tomcat對象的start教程詳解
這篇文章主要介紹了Spring Boot啟動過程(五)之Springboot內嵌Tomcat對象的start的相關資料,需要的朋友可以參考下2017-04-04

