uniapp下載excel(在線預覽效果),后端用springboot


看了網上很多文章,很多都是只給了后端或者只給的前端打開文檔微信那個openDocument的方法

而后端很多也只是給了返回流方法,這里看了很多總結下

首先后端要引入依賴

<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>

藍色的依賴必須要引入,第二個依賴應該不用,不過先貼上,以防下面的java代碼需要
這里貼上controller的方法
    @PostMapping("/download")
    public R downLoad(@RequestBody FyGroupProjectItemUserDTO itemUserList, HttpServletResponse response) {

        try {
            //命名列名
            List<String> cellNameList = new ArrayList<>();
            cellNameList.add("id");
            cellNameList.add("名字");
            cellNameList.add("當日報數");
            cellNameList.add("累計報數");

            //給文件命名

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
            String dateformat = simpleDateFormat.format(new Date());
            String excelPath = "報數記錄" + dateformat + ".xls";
            //給表命名
            String title = "報數記錄";
            HSSFWorkbook excel = Excel.createExcel(title, cellNameList);
            int row = 1;
            //從數據庫讀數據然后循環寫入
            List<FyGroupProjectItemUser> itemUserListList = itemUserList.getList();
            for (FyGroupProjectItemUser itemUser : itemUserListList) {
                List<String> excelData = new ArrayList<>();
                excelData.add(itemUser.getId().toString());
                excelData.add(itemUser.getName().toString());
                excelData.add(itemUser.getCount().toString());
                excelData.add(itemUser.getNewCount().toString());
                excel = Excel.createExcelData(excel, excelData, row);
                row++;
            }
            //輸出數據
            //FileOutputStream fos = new FileOutputStream(excelPath);
            OutputStream out = null;
            //防止中文亂碼
            String headStr = "attachment; filename=\"" + new String(excelPath.getBytes("utf-8"), "ISO8859-1") + "\"";
            //response.setContentType("octets/stream");
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", headStr);
            out = response.getOutputStream();
            //將excel寫入流
            excel.write(out);
            out.flush();
            out.close();
            System.out.println("寫出去了");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

返回的類型R是我用了springblade的一個自帶的類型,里面封裝了很多構造方法,便於返回, 不用的話直接void,或者隨便返回類型就行,反正都是寫出去的流,返回null或者不返回都行

這里貼上uniapp的前端代碼:

downLoadExcel() {
                wx.showLoading({
                    title: '加載中',
                })
                console.log("list",this.projectList)
                for (var i = 0; i < this.projectList.length; i++) {
                    this.projectList[i].newCount = this.projectList[i].totalNum  //這里我做下數據處理,可忽略
                }
                wx.request({
                    url: 'http://localhost:8886/count/export/download', //調用后台接口的全路徑
                    data: {
                        list: this.projectList
                    },
                    method: "POST",
                    header: {
                        // 'Content-type': 'application/x-www-form-urlencoded',
                        'Content-type': 'application/json',  //這里指定的數據要和后端對應 // 'Cookie': app.globalData.userInfo && app.globalData.userInfo.cookie ? app.globalData.userInfo.cookie : '',
                    },
                    responseType: 'arraybuffer', //此處是請求文件流,必須帶入的屬性
                    success: res => {
                        if (res.statusCode === 200) {
                            console.log("200")
                            const fs = wx.getFileSystemManager(); //獲取全局唯一的文件管理器
                            fs.writeFile({
                                // filePath: wx.env.USER_DATA_PATH + "/身體成分報告.pdf", // wx.env.USER_DATA_PATH 指定臨時文件存入的路徑,后面字符串自定義
                                filePath: wx.env.USER_DATA_PATH + "/test.xls", // wx.env.USER_DATA_PATH 指定臨時文件存入的路徑,后面字符串自定義
                                data: res.data,
                                encoding: "binary", //二進制流文件必須是 binary
                                success(res) {
                                    console.log("success(res)",res)
                                    
                                    wx.openDocument({ // 打開文檔
                                        filePath: wx.env.USER_DATA_PATH + "/test.xls", //拿上面存入的文件路徑
                                        // showMenu: true, // 顯示右上角菜單
                                        success: function(res) {
                                            console.log("successfun",res)
                                            setTimeout(() => {
                                                wx.hideLoading()
                                            }, 500)
                                        },fail:function(res){
                                            console.log("failfun",res)
                                        }
                                    })
                                },
                                fail(res){
                                    console.log("fail",res)
                                }
                            })
                        }else{
                            console.log("不是200")
                        }
                        console.log("success",res)
                    },
                    fail:res =>{
                        console.log("fail",res)
                    }
                })
            },

 這樣就可以做到在線預覽了

看網上說也可以上傳到服務器,讓服務器返回一個url,然后再打開這樣

應該也可以這樣,可能這樣更好, 不過可能比較耗服務器,先寫到這,上面的代碼直接復制就可,數據換成 自己的數據即可


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM