微软 Office Web Viewer 的使用

标题在浏览器阅读word,excel,pptx的offic文件,可以使用微软的开发接口

准备工作:需要有个后端接口,可以通过这个接口获取文件,我这里的接口读取的是本地的excel文件,是写死的,不需要指定文件名,你们可以写一个向接口发送指定文件名和路径的接口,读取想要的文件。
java接口代码如下:
这里有一点需要注意,就是函数的返回值要写成void,我刚开始写的是 HttpServletResponse,然后发现向接口发送请求的时候报如下的错:

No converter for XXX with preset Content-Type ‘application/vnd.ms-excel;charset=utf-8

接口:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping(value = "/file")
@ResponseBody
public class FileController {
    
    

    @RequestMapping("download")
    public void downloadFile(HttpServletResponse response){
    
    
        System.out.println("接收到了下载文件的请求");
        String path = "D:/ability.xlsx";
        try {
    
    
            // path是指欲下载的文件的路径。
            File file = new File(path);
            // 取得文件名。
            String filename = file.getName();
            // 取得文件的后缀名。
            String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();

            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
    
    
            ex.printStackTrace();
        }
    }

}

然后在前端页面写入如下js代码

<div>
    <el-button type="primary" @click="testfile">预览文件</el-button>
</div>

const testfile = () => {
    
    
  let routeUrl = "http://域名/file/download"; //文件路径
  let url = encodeURIComponent(routeUrl);
  let officeUrl = "http://view.officeapps.live.com/op/view.aspx?src=" + url;
  window.open(officeUrl, "_target");
};

个人认为实现的原理是微软的服务器读取到我们的文件,然后将渲染结果发送给我们,所以routeUrl 中的地址必须是公网ip地址,否则无法使用。
使用效果如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44019553/article/details/125497013