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

下載效果圖:

一、上傳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>
僅允許導(dǎo)入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)建的實體,要意義對應(yī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è)置為字符串再作為數(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"
>導(dǎo)出</a
>
</el-button>
const exportInfo = () => {
ElMessage({
message: "請稍等",
type: "warning",
})
}
四、下載excel后端代碼
Controller層
/**
* 導(dǎo)出表格
*
* @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("導(dǎo)出表格");
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;
/***
* 標(biāo)題行開始位置
*/
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);
}
/**
* 生成標(biāo)題(第零行創(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();
// 設(shè)置這些樣式
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
// 設(shè)置邊框
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("宋體");
// 把字體 應(yīng)用到當(dāng)前樣式
style.setFont(font);
//style設(shè)置好后,為cell設(shè)置樣式
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();
// 設(shè)置這些樣式
style.setAlignment(HorizontalAlignment.CENTER);//水平居中
style.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
// 設(shè)置邊框
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("宋體");
// 把字體 應(yīng)用到當(dāng)前樣式
style.setFont(font);
//style設(shè)置好后,為cell設(shè)置樣式
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("調(diào)用" + method + "方法");
//反射調(diào)用
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();
}
}
/**
* 自動伸縮列(如非必要,請勿打開此方法,耗內(nèi)存)
*
* @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 {
//生成表格的不可重復(fù)名
Date date = new Date();
// 初始化workbook
initHSSFWorkbook(sheetName);
// 表頭行
createHeadRow(titleMap);
// 文本行
createContentRow(list, titleMap);
//輸出Excel文件
OutputStream output=response.getOutputStream();
response.reset();
//設(shè)置響應(yīng)頭,
response.setHeader("Content-disposition", "attachment; filename=teacher.xls");
response.setContentType("application/msexcel");
workbook.write(output);
output.close();
}
}到此這篇關(guān)于Java+element實現(xiàn)excel的導(dǎo)入和導(dǎo)出的文章就介紹到這了,更多相關(guān)Java element excel導(dǎo)入和導(dǎo)出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java利用EasyExcel實現(xiàn)導(dǎo)出導(dǎo)入功能的示例代碼
- java利用easyexcel實現(xiàn)導(dǎo)入與導(dǎo)出功能
- Java實現(xiàn)Excel導(dǎo)入導(dǎo)出操作詳解
- Java+EasyExcel實現(xiàn)文件的導(dǎo)入導(dǎo)出
- Java用POI導(dǎo)入導(dǎo)出Excel實例分析
- java使用EasyExcel導(dǎo)入導(dǎo)出excel
- Java中Easypoi實現(xiàn)excel多sheet表導(dǎo)入導(dǎo)出功能
- java實現(xiàn)Excel的導(dǎo)入導(dǎo)出
相關(guān)文章
淺談mybatis mapper.xml文件中$和#的區(qū)別
這篇文章主要介紹了淺談mybatis mapper.xml文件中$和#的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11
讀取Java文件到byte數(shù)組的三種方法(總結(jié))
下面小編就為大家?guī)硪黄x取Java文件到byte數(shù)組的三種方法(總結(jié))。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-08-08
SpringBoot如何實現(xiàn)starter原理詳解
這篇文章主要介紹了SpringBoot如何實現(xiàn)starter原理詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
JNDI在JavaEE中的角色_動力節(jié)點Java學(xué)院整理
這篇文章主要介紹了JNDI在JavaEE中的角色,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08

