zoukankan      html  css  js  c++  java
  • 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,然后再打开这样

    应该也可以这样,可能这样更好, 不过可能比较耗服务器,先写到这,上面的代码直接复制就可,数据换成 自己的数据即可

  • 相关阅读:
    Elastic Search快速上手(2):将数据存入ES
    汇编学习笔记(24)
    汇编学习笔记(23)
    汇编学习笔记(22)
    汇编学习笔记(21)
    汇编学习笔记(20)
    汇编学习笔记(19)
    汇编学习笔记(18)
    汇编学习笔记(17)
    汇编学习笔记(16)
  • 原文地址:https://www.cnblogs.com/share-record/p/14334223.html
Copyright © 2011-2022 走看看