Springboot實(shí)現(xiàn)前后端分離excel下載
Springboot前后端分離excel下載
現(xiàn)在公司的技術(shù)棧是springboot作為后端,前端是vue, 現(xiàn)在要做excel的導(dǎo)出功能, 之前沒(méi)做過(guò),寫(xiě)一下記錄下.
springboot版本是2.0.6 poi 3.14 ,jdk1.8
類上面的注解是: @RestController
/**
* 導(dǎo)出excel
*
*/
@GetMapping("export")
public void exportExcel() {
XSSFWorkbook workbook = placeStatService.exportExcel();
// 設(shè)置生成的Excel的文件名,并以中文進(jìn)行編碼
String fileName = null;
try {
fileName = URLEncoder.encode("房間預(yù)約使用統(tǒng)計(jì)表" + ".xlsx", "utf-8").replaceAll("\\+", "%20");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
// 響應(yīng)類型,編碼
response.setContentType("application/octet-stream;charset=UTF-8");
try {
// 形成輸出流
OutputStream osOut = response.getOutputStream();
// 將指定的字節(jié)寫(xiě)入此輸出流
workbook.write(osOut);
// 刷新此輸出流并強(qiáng)制將所有緩沖的輸出字節(jié)被寫(xiě)出
osOut.flush();
// 關(guān)閉流
osOut.close();
workbook.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public XSSFWorkbook exportExcel) {
List<RoomOrderDetailModel> roomOrdersList = getRoomOrderList();
XSSFWorkbook data = ExcelUtil.setExcelData(roomOrdersList);
return data;
}
package com.util;
import com.curefun.place.model.RoomOrderDetailModel;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* @author excel 工具類. 導(dǎo)出功能
*/
public class ExcelUtil {
/**
* 數(shù)據(jù)導(dǎo)出, 獲取一個(gè)excel對(duì)象
*
* @param
*/
public static XSSFWorkbook setExcelData(List<RoomOrderDetailModel> orderDetailModels) {
//創(chuàng)建一個(gè)book,對(duì)應(yīng)一個(gè)Excel文件
XSSFWorkbook workbook = new XSSFWorkbook();
//在book中添加一個(gè)sheet,對(duì)應(yīng)Excel文件中的sheet
XSSFSheet sheet = workbook.createSheet("教室預(yù)約使用記錄");
//設(shè)置六列的寬度
sheet.setColumnWidth(0, 4000);
sheet.setColumnWidth(1, 3000);
sheet.setColumnWidth(2, 3800);
sheet.setColumnWidth(3, 2800);
sheet.setColumnWidth(4, 3200);
sheet.setColumnWidth(5, 3600);
sheet.setColumnWidth(6, 2850);
//居中的樣式
XSSFCellStyle centerStyle = getCenterStyle(workbook);
// 第三步,在sheet中添加表頭第0行
XSSFRow row0 = sheet.createRow(0);
setFirstRow(centerStyle, row0);
int rowNum = 1;
for (RoomOrderDetailModel model : orderDetailModels) {
XSSFRow row = sheet.createRow(rowNum);
row.createCell(0).setCellValue(rowNum);
rowNum++;
row.createCell(1).setCellValue(model.getBuildingName());
row.createCell(2).setCellValue(model.getRoomNo());
row.createCell(3).setCellValue(model.getRoomName());
row.createCell(4).setCellValue(model.getEventType());
row.createCell(5).setCellValue(model.getEventName());
row.createCell(6).setCellValue(model.getUserRealName());
}
return workbook;
}
/**
* 獲取居中的樣式.
*
* @param workbook
* @return
*/
private static XSSFCellStyle getCenterStyle(XSSFWorkbook workbook) {
XSSFCellStyle cellStyle = workbook.createCellStyle();
//設(shè)置水平對(duì)齊的樣式為居中對(duì)齊;
cellStyle.setAlignment(HorizontalAlignment.CENTER);
//垂直居中
cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);
return cellStyle;
}
/**
* 設(shè)置第一行的表頭
*
* @param centerStyle
* @param row
*/
private static void setFirstRow(XSSFCellStyle centerStyle, XSSFRow row) {
XSSFCell cell0 = row.createCell(0);
cell0.setCellValue("序號(hào)");
cell0.setCellStyle(centerStyle);
XSSFCell cell1 = row.createCell(1);
cell1.setCellValue("樓棟信息");
cell1.setCellStyle(centerStyle);
XSSFCell cell2 = row.createCell(2);
cell2.setCellValue("房號(hào)");
cell2.setCellStyle(centerStyle);
XSSFCell cell3 = row.createCell(3);
cell3.setCellValue("房間名稱");
cell3.setCellStyle(centerStyle);
XSSFCell cell4 = row.createCell(4);
cell4.setCellValue("活動(dòng)類型");
cell4.setCellStyle(centerStyle);
XSSFCell cell5 = row.createCell(5);
cell5.setCellValue("活動(dòng)名稱");
cell5.setCellStyle(centerStyle);
XSSFCell cell6 = row.createCell(6);
cell6.setCellValue("使用人");
cell6.setCellStyle(centerStyle);
/**
其實(shí)完全使用這種方式, 會(huì)更加的簡(jiǎn)單,便于修改
List<String> title = Stream.of("序號(hào)", "專業(yè)", "班級(jí)", "課程名稱", "課程內(nèi)容", "授課教師", "授課時(shí)長(zhǎng)", "授課時(shí)間", "學(xué)分", "授課房間")
.collect(Collectors.toList());
for (int i = 0; i < title.size(); i++) {
XSSFCell cell = row.createCell(i);
cell.setCellValue(title.get(i));
cell.setCellStyle(centerStyle);
}
*/
}
}
其實(shí)使用很簡(jiǎn)單,就是excel的文件名需要進(jìn)行編碼,這個(gè)需要注意,其他沒(méi)啥的了.
前后端分離Excle下載亂碼問(wèn)題
前端:vue+elementUI
后端:springCloud
前端請(qǐng)求方式 : ajax請(qǐng)求
this.$.ajax({
url :this.url + "/",
type : 'post',
data : formData,
contentType: false,
processData: false,
xhrFields: {withCredentials: true, responseType:'arraybuffer'},
headers : {'Access-Control-Allow-Origin': '*', "Authorization": this.ajaxRequest.getToken()},
success: function (res, textStatus, request) {
var downloadFile = document.createElement('a');
let blob = new Blob([res], {type : "application/vnd.ms-excel;charset=UTF-8"});
downloadFile.href = window.URL.createObjectURL(blob);
console.log(request.getResponseHeader('Content-disposition'));
downloadFile.download =
decodeURI(request.getResponseHeader('Content-disposition').split('filename=')[1] );
downloadFile.click();
window.URL.revokeObjectURL(downloadFile.href);
},
error : function (res) {
console.log(res)
}
})
后端處理:導(dǎo)出文件處理
// 輸出Excel文件
OutputStream out = null;
out = response.getOutputStream();
response.reset();
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF8"));
response.setContentType("application/vnd.ms-excel; charset=utf-8");
// 輸出Excel內(nèi)容,生成Excel文件
wb.write(out);
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java利用for循環(huán)輸出空心三角形、空心菱形和空心矩形的代碼
今天小編就為大家分享一篇關(guān)于Java利用for循環(huán)輸出空心三角形、空心菱形和空心矩形的代碼,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧2018-12-12
Java中List.of()和Arrays.asList()的區(qū)別及原因分析
這篇文章主要介紹了Java中List.of()和Arrays.asList()的區(qū)別及原因分析,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09
推薦兩款java開(kāi)發(fā)實(shí)用工具 hutool 和 lombok
通過(guò)本文給大家推薦兩款java開(kāi)發(fā)實(shí)用工具 hutool 和 lombok,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2021-04-04
Java代碼審計(jì)的一些基礎(chǔ)知識(shí)你知道嗎
這篇文章主要介紹了基于Java的代碼審計(jì)功能的基礎(chǔ)知識(shí),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2021-09-09
利用synchronized實(shí)現(xiàn)線程同步的案例講解
這篇文章主要介紹了利用synchronized實(shí)現(xiàn)線程同步的案例講解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-02-02
Java設(shè)置Map過(guò)期時(shí)間的的幾種方法舉例詳解
本文詳細(xì)介紹了Java中使用輕量級(jí)緩存組件ExpiringMap以及Guava的LoadingCache緩存機(jī)制,ExpiringMap提供了Map自動(dòng)過(guò)期、監(jiān)聽(tīng)事件等功能,而LoadingCache提供了緩存回收、數(shù)據(jù)加載等高級(jí)功能,兩者為Java項(xiàng)目提供了有效的數(shù)據(jù)管理和緩存解決方案,需要的朋友可以參考下2024-10-10
Java使用DateTimeFormatter格式化輸入的日期時(shí)間
這篇文章主要介紹了Java使用DateTimeFormatter格式化輸入的日期時(shí)間,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-01-01
java編程創(chuàng)建型設(shè)計(jì)模式單例模式的七種示例
這篇文章主要為大家介紹了java編程中創(chuàng)建型設(shè)計(jì)模式之單例模式的示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-02-02

