溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

Springboot怎么實(shí)現(xiàn)前后端分離excel下載

發(fā)布時(shí)間:2021-11-11 11:07:07 來(lái)源:億速云 閱讀:300 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本篇內(nèi)容介紹了“Springboot怎么實(shí)現(xiàn)前后端分離excel下載”的有關(guān)知識(shí),在實(shí)際案例的操作過(guò)程中,不少人都會(huì)遇到這樣的困境,接下來(lái)就讓小編帶領(lǐng)大家學(xué)習(xí)一下如何處理這些情況吧!希望大家仔細(xì)閱讀,能夠?qū)W有所成!

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

類(lèi)上面的注解是: @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)類(lèi)型,編碼
        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 工具類(lèi). 導(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("房間名稱(chēng)");
        cell3.setCellStyle(centerStyle);
        XSSFCell cell4 = row.createCell(4);
        cell4.setCellValue("活動(dòng)類(lèi)型");
        cell4.setCellStyle(centerStyle);
        XSSFCell cell5 = row.createCell(5);
        cell5.setCellValue("活動(dòng)名稱(chē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)", "專(zhuān)業(yè)", "班級(jí)", "課程名稱(chēng)", "課程內(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);

“Springboot怎么實(shí)現(xiàn)前后端分離excel下載”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識(shí)可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實(shí)用文章!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI