Java+element實現(xiàn)excel的導入和導出
本項目是前端vue3,后端springboot開發(fā) 需求為:前端導入表格,后端處理表格存儲數(shù)據(jù),點擊按鈕可以導出表格。
上傳效果:前端點擊上傳按鈕,會跳出選擇文件框,選擇文件,點擊上傳。
導出效果:前端點擊導出按鈕,會跳出下載框,選擇位置自動下載。
上傳效果圖:

下載效果圖:

一、上傳excel前端代碼
<el-upload
ref="file"
class="upload-demo"
:limit="1"
accept=".xlsx, .xls"
action="http://localhost:8081/admin/perform/importexcel"
auto-upload="false"
>
<template #trigger>
<el-button type="primary">選擇文件</el-button>
</template>
<el-button
class="ml-3"
style="margin-left: 20px"
type="success"
@click="submitUpload"
>
上傳文件
</el-button>
僅允許導入xls、xlsx格式文件。
</el-upload>import { ref, reactive, computed } from "vue"
import { ElMessage, UploadInstance } from "element-plus"
const file = ref<UploadInstance>()
const submitUpload = () => {
file.value!.submit()
ElMessage({
message: "上傳成功",
type: "success",
})
window.location.reload()
}
效果圖

二、上傳excel后端代碼
Controller層
@PostMapping("/importexcel")
public Result importData(MultipartFile file) throws Exception {
return performService.importData(file.getInputStream());
}
Service層
@Override
public Result importData(InputStream inputStream) throws IOException {
// Perform根據(jù)自己表格的表頭創(chuàng)建的實體,要意義對應
List<Perform> res = new ArrayList<>();
try {
ins = (FileInputStream) inputStream;
//true xls文件,false xlsx文件
Workbook workbook = null;
// XSSFWorkbook instance of HSSFWorkbook 所以通用
workbook = new XSSFWorkbook(ins);
//獲取工作表
Sheet sheet = workbook.getSheetAt(0);
//獲取表頭
Row rowHead = sheet.getRow(0);
//判斷表頭是否正確
if (rowHead.getPhysicalNumberOfCells() < 1) {
return Result.error("表頭錯誤");
}
//獲取數(shù)據(jù)
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
//獲取第一行的用戶信息
Row row = sheet.getRow(i);
String tId;
if (row.getCell(0) == null) {
tId = "";
row.createCell(0).setCellValue(tId);
} else {
//先設置為字符串再作為數(shù)字讀出來
row.getCell(0).setCellType(CellType.STRING);
tId = row.getCell(0).getStringCellValue();
}
String tName;
if (row.getCell(1) == null) {
tName = "";
row.createCell(1).setCellValue(tName);
} else {
tName = row.getCell(1).getStringCellValue();
}
String tDept;
if (row.getCell(2) == null) {
tDept = "";
row.createCell(2).setCellValue(tDept);
} else {
tDept = row.getCell(2).getStringCellValue();
}
....................
Perorm perform=new Perform()
xxxset創(chuàng)建實體
System.out.println(perform);
res.add(perform);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ins != null) {
try {
ins.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
new Thread(() -> {
//批處理比較快
batchInsert(res);
}).start();
return Result.success(res);
}
/**
* 批量插入更快
*
* @param performList
*/
private void batchInsert(List<Perform> performList) {
SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
performList.stream().forEach(perform -> {
performMapper.insert(perform);
});
sqlSession.commit();
sqlSession.clearCache();
}
三、下載excel前端代碼
<el-button
type="warning"
style="width: 100px"
@click="exportInfo()"
>
<a href="http://localhost:8081/admin/perform/exportexcel" rel="external nofollow"
>導出</a
>
</el-button>
const exportInfo = () => {
ElMessage({
message: "請稍等",
type: "warning",
})
}
四、下載excel后端代碼
Controller層
/**
* 導出表格
*
* @return
*/
@GetMapping("/exportexcel")
public void exportExcel(HttpServletResponse response) throws Exception {
performService.exportExcel(response);
}
Service層
@Override
public void exportExcel(HttpServletResponse response) throws IOException {
System.out.println("導出表格");
List<Perform> list = performMapper.selectList(new QueryWrapper<>());
String sheetName = "教師業(yè)績表";
Map<String, String> titleMap = new LinkedHashMap<>();
titleMap.put("tId", "教師工號");
titleMap.put("tName", "教師姓名");
.....根據(jù)自己的表頭來
ExportExcel.excelExport(response, list, titleMap, sheetName);
}
ExportExcel類:
package com.performance.back.common.utils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.performance.back.admin.dao.entity.Perform;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
/**
* @ClassName ExportExcel
* @Descriotion TODO
* @Author nitaotao
* @Date 2022/11/14 11:55
* @Version 1.0
**/
public class ExportExcel {
private ExportExcel() {
}
/***
* 工作簿
*/
private static HSSFWorkbook workbook;
/***
* sheet
*/
private static HSSFSheet sheet;
/***
* 標題行開始位置
*/
private static final int TITLE_START_POSITION = 0;
/***
* 時間行開始位置
*/
private static final int DATEHEAD_START_POSITION = 1;
/***
* 表頭行開始位置
*/
private static final int HEAD_START_POSITION = 0;
/***
* 文本行開始位置
*/
private static final int CONTENT_START_POSITION = 1;
/***
*
* @param sheetName
* sheetName
*/
private static void initHSSFWorkbook(String sheetName) {
workbook = new HSSFWorkbook();
sheet = workbook.createSheet(sheetName);
sheet.setDefaultColumnWidth(15);
}
/**
* 生成標題(第零行創(chuàng)建)
*
* @param titleMap 對象屬性名稱->表頭顯示名稱
* @param sheetName sheet名稱
*/
private static void createTitleRow(Map<String, String> titleMap, String sheetName) {
CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, titleMap.size() - 1);
sheet.addMergedRegion(titleRange);
HSSFRow titleRow = sheet.createRow(TITLE_START_POSITION);
HSSFCell titleCell = titleRow.createCell(0);
titleCell.setCellValue(sheetName);
}
/**
* 創(chuàng)建時間行(第一行創(chuàng)建)
*
* @param titleMap 對象屬性名稱->表頭顯示名稱
*/
private static void createDateHeadRow(Map<String, String> titleMap) {
CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, titleMap.size() - 1);
sheet.addMergedRegion(dateRange);
HSSFRow dateRow = sheet.createRow(DATEHEAD_START_POSITION);
HSSFCell dateCell = dateRow.createCell(0);
dateCell.setCellValue(new SimpleDateFormat("yyyy年MM月dd日").format(new Date()));
}
/**
* 創(chuàng)建表頭行(第二行創(chuàng)建)
*
* @param titleMap 對象屬性名稱->表頭顯示名稱
*/
private static void createHeadRow(Map<String, String> titleMap) {
// 第1行創(chuàng)建
HSSFRow headRow = sheet.createRow(HEAD_START_POSITION);
headRow.setHeight((short) 900);
int i = 0;
for (String entry : titleMap.keySet()) {
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
// 設置邊框
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
// 自動換行
style.setWrapText(true);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 10);
font.setColor(IndexedColors.WHITE.index);
font.setBold(false);
font.setFontName("宋體");
// 把字體 應用到當前樣式
style.setFont(font);
//style設置好后,為cell設置樣式
HSSFCell headCell = headRow.createCell(i);
headCell.setCellValue(titleMap.get(entry));
if (i > 14) {
// 背景色
style.setFillForegroundColor(IndexedColors.BLUE.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.BLUE.index);
} else if (i > 10) {
style.setFillForegroundColor(IndexedColors.BLACK.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.BLACK.index);
} else if (i > 7) {
style.setFillForegroundColor(IndexedColors.BLUE.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.BLUE.index);
} else if (i >4) {
style.setFillForegroundColor(IndexedColors.RED.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.RED.index);
} else {
style.setFillForegroundColor(IndexedColors.GREEN.index);
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
style.setFillBackgroundColor(IndexedColors.GREEN.index);
}
headCell.setCellStyle(style);
i++;
}
}
/**
* @param dataList 對象數(shù)據(jù)集合
* @param titleMap 表頭 信息
*/
private static void createContentRow(List<?> dataList, Map<String, String> titleMap) {
try {
int i = 0;
// 生成一個樣式
HSSFCellStyle style = workbook.createCellStyle();
// 設置這些樣式
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
// 設置邊框
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
style.setBorderTop(BorderStyle.THIN);
// 自動換行
style.setWrapText(true);
// 生成一個字體
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 10);
font.setColor(IndexedColors.BLACK.index);
font.setBold(false);
font.setFontName("宋體");
// 把字體 應用到當前樣式
style.setFont(font);
//style設置好后,為cell設置樣式
for (Object obj : dataList) {
HSSFRow textRow = sheet.createRow(CONTENT_START_POSITION + i);
int j = 0;
for (String entry : titleMap.keySet()) {
//屬性名駝峰式
String method = "get" + entry.substring(0, 1).toUpperCase() + entry.substring(1);
// System.out.println("調用" + method + "方法");
//反射調用
Method m = obj.getClass().getMethod(method, null);
Object value = m.invoke(obj, null);
HSSFCell textcell = textRow.createCell(j);
if (ObjectUtils.isNotEmpty(value)) {
textcell.setCellValue(value.toString());
} else {
textcell.setCellValue("");
}
textcell.setCellStyle(style);
j++;
}
i++;
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 自動伸縮列(如非必要,請勿打開此方法,耗內存)
*
* @param size 列數(shù)
*/
private static void autoSizeColumn(Integer size) {
for (int j = 0; j < size; j++) {
sheet.autoSizeColumn(j);
}
}
public static void excelExport( HttpServletResponse response, List<Perform> list, Map<String, String> titleMap, String sheetName) throws IOException {
//生成表格的不可重復名
Date date = new Date();
// 初始化workbook
initHSSFWorkbook(sheetName);
// 表頭行
createHeadRow(titleMap);
// 文本行
createContentRow(list, titleMap);
//輸出Excel文件
OutputStream output=response.getOutputStream();
response.reset();
//設置響應頭,
response.setHeader("Content-disposition", "attachment; filename=teacher.xls");
response.setContentType("application/msexcel");
workbook.write(output);
output.close();
}
}到此這篇關于Java+element實現(xiàn)excel的導入和導出的文章就介紹到這了,更多相關Java element excel導入和導出內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Mybatis如何使用ognl表達式實現(xiàn)動態(tài)sql
這篇文章主要介紹了Mybatis使用ognl表達式實現(xiàn)動態(tài)sql的操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06
Java如何利用Mybatis進行數(shù)據(jù)權限控制詳解
這篇文章主要介紹了Java如何利用Mybatis進行數(shù)據(jù)權限控制詳解,數(shù)據(jù)權限控制最終的效果是會要求在同一個數(shù)據(jù)請求方法中,根據(jù)不同的權限返回不同的數(shù)據(jù)集,而且無需并且不能由研發(fā)編碼控制。,需要的朋友可以參考下2019-06-06
Java日志logback的使用配置和logback.xml解讀
這篇文章主要介紹了Java日志logback的使用配置和logback.xml解讀,具有很好的價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-06-06
spring boot實現(xiàn)上傳圖片并在頁面上顯示及遇到的問題小結
最近在使用spring boot搭建網站的過程之中遇到了有點小問題,最終解決方案是在main目錄下新建了一個webapp文件夾,并且對其路徑進行了配置,本文重點給大家介紹spring boot實現(xiàn)上傳圖片并在頁面上顯示功能,需要的朋友參考下吧2017-12-12

