用vue+springboot下載和上傳excel文件

CSDN鏈接:https://blog.csdn.net/sinat_27537929/article/details/98059599

需求

  1. 前端發(fā)送下載請求
  2. 后端接收請求问词,從數(shù)據(jù)庫拿出數(shù)據(jù)九榔,寫成excel格式,傳給前端
  3. 前端拿到excel進(jìn)行下載
  4. 在excel中增加數(shù)據(jù)
  5. 將新的excel上傳給服務(wù)器

環(huán)境

  1. 前端vue+ElementUI
  2. 后端springboot+mybatisplus+mysql
  3. 后端生成excel用到org.apache.poi

下載

html
<el-button type="primary" @click="exportWord" icon="el-icon-download" plain>導(dǎo)出</el-button>
js
    exportWord () {
      this.$axios.post('/web/xxxxxx/export', {}, {
        responseType: 'blob'
      }).then(res => {
        let blob = new Blob([res.data], { type: 'application/ms-excel;charset=utf-8' });
        let downloadElement = document.createElement('a');
        let href = window.URL.createObjectURL(blob); //創(chuàng)建下載的鏈接
        downloadElement.href = href;
        downloadElement.download = 'forbidden-words.xls'; //下載后文件名
        document.body.appendChild(downloadElement);
        downloadElement.click(); //點擊下載
        document.body.removeChild(downloadElement); //下載完成移除元素
        window.URL.revokeObjectURL(href); //釋放掉blob對象
      })
    }
controller
    @PostMapping("/export")
    public void exportXXXXXXWords(HttpServletResponse response) {
        List<ForbiddenWord> forbiddenList;
        try {
            // get your data
            wordList = wordService.getWords();
            // 設(shè)置excel第一行的標(biāo)題
            String[] titleRow = new String[]{"單詞", "級別"};
            List<String[]> data = new LinkedList<String[]>();
            data.add(0, titleRow);
            for (int i = 0; i < wordList.size(); i++) {
                Word word = wordList.get(i);
                data.add(new String[]{
                        word.getWord(),
                        word.getLevel().toString()
                });
            }
            Map<String, List<String[]>> exportData = new HashMap<String, List<String[]>>();
            // 設(shè)置sheet的名稱
            exportData.put("Your sheet name", data);
            String strResult = FileUtils.createExcelFile(response, exportData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
FileUtils
    /**
     * 直接生成文件流返回給前端
     *
     * @param response
     * @param exportData
     * @return
     */
    public static String createExcelFile(HttpServletResponse response, Map<String, List<String[]>> exportData) {
        OutputStream outputStream = null;
        try {
            Workbook wb = new HSSFWorkbook();

            for (String sheetName : exportData.keySet()) {
                Sheet sheet = wb.createSheet(sheetName);
                List<String[]> rowData = exportData.get(sheetName);
                for (int i = 0; i < rowData.size(); i++) {
                    String[] cellData = rowData.get(i);
                    Row row = sheet.createRow(i);
                    for (int j = 0; j < cellData.length; j++) {
                        Cell cell = row.createCell(j);
                        cell.setCellValue(cellData[j]);
                    }
                }
            }
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.flushBuffer();
            outputStream = response.getOutputStream();
            wb.write(outputStream);
        } catch (IOException ex) {
            ex.printStackTrace();
            return "failure";
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.flush();
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "success";
    }

上傳

首先被碗,因為公司封裝了axios窿冯,每次發(fā)送都需要帶著token等數(shù)據(jù)枣抱,所以不能直接用ElementUI中el-upload組件的action解愤。
el-upload中有個屬性http-request:覆蓋默認(rèn)的上傳行為骤素,可以自定義上傳的實現(xiàn)家淤,接收類型是function异剥,就是他了。
這里我用了auto-upload="false"這個屬性絮重,即“是否在選取文件后立即進(jìn)行上傳”選擇不立即上傳冤寿,所以多了一個按鈕來實現(xiàn)點擊觸發(fā)上傳歹苦。

html
    <el-upload
        ref="upload"
        action
        :multiple="false"
        :file-list="fileList"
        :auto-upload="false"
        :limit="1"
        :http-request="importWordConfirm"
      >
        <el-button slot="trigger" size="small" type="primary" plain>選取文件</el-button>
        <el-button
          style="margin-left: 10px;"
          size="small"
          type="success"
          @click="submitUpload"
          plain
        >上傳到服務(wù)器</el-button>
      </el-upload>
js
    submitUpload () {
      this.$refs.upload.submit();
    },
    importWordConfirm (item) {
      const fileObj = item.file
      const formData = new FormData()
      formData.append('file', fileObj)
      this.$axios.post('/web/xxxxxx/import', formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      }).then(res => {
        // do something
      })
    }

controller

    @PostMapping("/import")
    public ApiResult importXXXXXXWords(
            @RequestParam("file") MultipartFile uploadFile,
            HttpServletRequest request) throws Exception {
        try {
            if (uploadFile == null) {
                //判斷文件大小
                return failure("-1", "文件不存在");
            }
            
            // 構(gòu)造臨時路徑來存儲上傳的文件
            // 這個路徑相對當(dāng)前應(yīng)用的目錄
            // Constant.UPLOAD_DIRECTORY是你自己存放文件的文件夾
            String uploadPath = request.getServletContext().getRealPath("/")
                    + File.separator + Constant.UPLOAD_DIRECTORY;

            //如果目錄不存在則創(chuàng)建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }

            String fileName = uploadFile.getOriginalFilename();
            String originalFileName = fileName
                    .substring(0, fileName.lastIndexOf("."));
            //獲取文件名后綴
            String suffix = fileName
                    .substring(fileName.lastIndexOf("."));
            String newFileName = originalFileName
                    + "_" + UUID.randomUUID().toString() + suffix;

            File file = new File(uploadPath, newFileName);
            try {
                uploadFile.transferTo(file);
            } catch (Exception e) {
                e.printStackTrace();
            }

            List<String[]> fileData = null;
            if (suffix.equals(".xls")) {
                fileData = FileUtils.readXlsFile(file.getAbsolutePath());
            } else if (suffix.equals(".xlsx")) {
                fileData = FileUtils.readXlsxFile(file.getAbsolutePath());
            } else {
                return failure("-2", "文件格式不正確");
            }

            // do something

            return success("解析文件成功");
        } catch (Exception e) {
            e.printStackTrace();
            return failure("-1", "更新有誤");
        }
    }
FileUtils
    public static List<String[]> readXlsFile(String filePath) {
        HSSFWorkbook workbook = null;
        List<String[]> list = new LinkedList<String[]>();
        try {
            workbook = new HSSFWorkbook(new FileInputStream(filePath));
            HSSFSheet sheet = workbook.getSheetAt(0);
            int rowNumber = sheet.getLastRowNum();
            for (int i = 0; i < rowNumber + 1; i++) {
                HSSFRow row = sheet.getRow(i);
                int lastCellNum = row.getLastCellNum();
                String[] cells = new String[lastCellNum];
                for (int j = 0; j < lastCellNum; j++) {
                    HSSFCell cell = row.getCell(j);
                    if (cell != null) {
                        cells[j] = cell.toString();
                    } else {
                        cells[j] = "";
                    }
                }
                list.add(cells);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //刪除標(biāo)題
        list.remove(0);
        return list;
    }

    public static List<String[]> readXlsxFile(String filePath) {
        XSSFWorkbook workbook = null;
        List<String[]> list = new LinkedList<String[]>();
        try {
            workbook = new XSSFWorkbook(new FileInputStream(filePath));
            XSSFSheet sheet = workbook.getSheetAt(0);
            int rowNumber = sheet.getLastRowNum();
            for (int i = 0; i < rowNumber + 1; i++) {
                XSSFRow row = sheet.getRow(i);
                int lastCellNum = row.getLastCellNum();
                String[] cells = new String[lastCellNum + 1];
                for (int j = 0; j < lastCellNum; j++) {
                    XSSFCell cell = row.getCell(j);
                    cells[j] = cell.toString();
                }
                list.add(cells);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //刪除標(biāo)題
        list.remove(0);
        return list;
    }

這里還要說兩個小插曲...

  • 當(dāng)時我想console.log(formData),結(jié)果發(fā)現(xiàn)console的結(jié)果是{}督怜,我以為沒有數(shù)據(jù)...后來看了別人的文章發(fā)現(xiàn)應(yīng)該這么用:console.log(formData.get('xxx'))
  • 由于公司封裝了axios殴瘦,然后每次post我都發(fā)現(xiàn)不太對...原來公司設(shè)置的http request攔截器默認(rèn)把post的Content-Type都改成了'application/x-www-form-urlencoded; charset=UTF-8'...可是,我需要'Content-Type': 'multipart/form-data'昂鸥堋r揭浮!姨蟋!然后默默地在攔截器里加了個判斷...

參考:

使用ElementUI中的upload組件上傳Excel文件
vue項目中實現(xiàn)下載后端返回的excel數(shù)據(jù)表格
Spring boot實現(xiàn)導(dǎo)出數(shù)據(jù)生成excel文件返回
萌新用vue + axios + formdata 上傳文件的爬坑之路

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末屉凯,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子眼溶,更是在濱河造成了極大的恐慌悠砚,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,576評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件偷仿,死亡現(xiàn)場離奇詭異哩簿,居然都是意外死亡,警方通過查閱死者的電腦和手機酝静,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,515評論 3 399
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來羡玛,“玉大人别智,你說我怎么就攤上這事〖诟澹” “怎么了薄榛?”我有些...
    開封第一講書人閱讀 168,017評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長让歼。 經(jīng)常有香客問我敞恋,道長,這世上最難降的妖魔是什么谋右? 我笑而不...
    開封第一講書人閱讀 59,626評論 1 296
  • 正文 為了忘掉前任硬猫,我火速辦了婚禮,結(jié)果婚禮上改执,老公的妹妹穿的比我還像新娘啸蜜。我一直安慰自己,他們只是感情好辈挂,可當(dāng)我...
    茶點故事閱讀 68,625評論 6 397
  • 文/花漫 我一把揭開白布衬横。 她就那樣靜靜地躺著,像睡著了一般终蒂。 火紅的嫁衣襯著肌膚如雪蜂林。 梳的紋絲不亂的頭發(fā)上遥诉,一...
    開封第一講書人閱讀 52,255評論 1 308
  • 那天,我揣著相機與錄音噪叙,去河邊找鬼矮锈。 笑死,一個胖子當(dāng)著我的面吹牛构眯,可吹牛的內(nèi)容都是我干的愕难。 我是一名探鬼主播,決...
    沈念sama閱讀 40,825評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼惫霸,長吁一口氣:“原來是場噩夢啊……” “哼猫缭!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起壹店,我...
    開封第一講書人閱讀 39,729評論 0 276
  • 序言:老撾萬榮一對情侶失蹤猜丹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后硅卢,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體射窒,經(jīng)...
    沈念sama閱讀 46,271評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,363評論 3 340
  • 正文 我和宋清朗相戀三年将塑,在試婚紗的時候發(fā)現(xiàn)自己被綠了脉顿。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,498評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡点寥,死狀恐怖艾疟,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情敢辩,我是刑警寧澤蔽莱,帶...
    沈念sama閱讀 36,183評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站戚长,受9級特大地震影響盗冷,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜同廉,卻給世界環(huán)境...
    茶點故事閱讀 41,867評論 3 333
  • 文/蒙蒙 一仪糖、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧恤溶,春花似錦乓诽、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,338評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至帐姻,卻和暖如春稠集,著一層夾襖步出監(jiān)牢的瞬間奶段,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,458評論 1 272
  • 我被黑心中介騙來泰國打工剥纷, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留痹籍,地道東北人。 一個月前我還...
    沈念sama閱讀 48,906評論 3 376
  • 正文 我出身青樓晦鞋,卻偏偏與公主長得像蹲缠,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子悠垛,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,507評論 2 359

推薦閱讀更多精彩內(nèi)容

  • 三國時期的曹操是個梟雄,為人卻生性多疑湾趾,為了達(dá)到目的不擇手段芭商,曹操在誤殺自己的干伯父呂伯奢之后,說起了寧可天下人負(fù)...
    零大人閱讀 293評論 0 0
  • 大帥和老媽去超市買東西了搀缠,果果睡著了铛楣,小淘當(dāng)然是去上學(xué)了,我一個人在家艺普,剛好有自己的私人空間蛉艾,好好享受一番吧! 之...
    7d89c4c06062閱讀 116評論 0 0
  • 一衷敌、實驗要求 從x3200開始輸入60個16位無符號整數(shù)作為學(xué)生成績,對它們按降序排序拓瞪,并把結(jié)果存放在從x4000...
    素理想閱讀 93評論 0 0
  • 襤褸衣衫心自正缴罗, 手持墨筆涂自像。 人善無語處靜默祭埂, 筆下生輝自成章面氓。
    鏡花水月之明月蒼天閱讀 262評論 0 0
  • 本文環(huán)境為:virtualbox+centos7.3+nginx 一. nginx安裝 1 nginx安裝環(huán)境 n...
    nickbi閱讀 618評論 0 1