Vue-集成其他插件问题总结

本文介绍了如何在Vue项目中集成XLSX库解析Excel文件并前端渲染,以及利用微软在线文档查看器实现Excel在线预览。首先,解决了XLSX导入错误的问题,通过修改引入方式为`import * as XLSX from 'xlsx';`成功解析和展示Excel内容。其次,展示了通过后台接口返回文件路径,前台利用微软在线查看器打开Excel的实现方法,提供了一种跨域预览文件的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. Vue 集成XLSX问题

1.1 XLSX 插件(不是直接预览,而是解析excel然后通过前端组件再次渲染)

在组件中引入xlsx import XLSX form ‘xlsx’
然后进行使用的话会报错
在这里插入图片描述

        // 请求网络接口
        loadRemoteFile(url) {
            let _this = this;
            this.readWorkbookFromRemoteFile(url, function (workbook) {
                _this.readWorkbook(workbook);
            });
        },
        // 从网络上读取某个excel文件,url必须同域,否则报错
        readWorkbookFromRemoteFile(url, callback) {
            var xhr = new XMLHttpRequest();
            xhr.open("get", url, true);
            xhr.responseType = "arraybuffer";
            xhr.onload = function (e) {
                if (xhr.status == 200) {
                    var data = new Uint8Array(xhr.response);
                    var workbook = XLSX.read(data, { type: "array" });
                    console.log(workbook, 'table 数据')
                    if (callback) callback(workbook);
                }
            };
            xhr.send();
        },
        // 读取 excel文件
        readWorkbook(workbook) {
            var sheetNames = workbook.SheetNames; // 工作表名称集合
            var worksheet = workbook.Sheets[sheetNames[0]]; // 这里我们只读取第一张sheet
            var csv = XLSX.utils.sheet_to_csv(worksheet);
            document.getElementById("result").innerHTML = this.csv2table(csv);
        },
        // 将csv转换成表格
        csv2table(csv) {
            var html = "<table>";
            var rows = csv.split("\n");
            rows.pop(); // 最后一行没用的
            rows.forEach(function (row, idx) {
                var columns = row.split(",");
                columns.unshift(idx + 1); // 添加行索引
                if (idx == 0) {
                    // 添加列索引
                    html += "<tr>";
                    for (var i = 0; i < columns.length; i++) {
                        html +=
                            "<th>" +
                            (i == 0 ? "" : String.fromCharCode(65 + i - 1)) +
                            "</th>";
                    }
                    html += "</tr>";
                }
                html += "<tr>";
                columns.forEach(function (column) {
                    html += "<td>" + column + "</td>";
                });
                html += "</tr>";
            });
            html += "</table>";
            return html;
        },

解决办法

将引入方式改为 ==> import * as XLSX from “xlsx”; 即可

1.2 利用微软在线文档查看器来查看Excel

前台代码

let showFilePath = 'https://view.officeapps.live.com/op/embed.aspx?src=' 地址 + '/fileModule/showFile-noEncrypt/' + 123456

window.open(showFilePath);

// src=XXX , 地址表示当前服务器地址 , 123456自定义后台参数可以自定义

后台代码

    /**
     * @param response
     */
    @GetMapping("/fileModule/showFile-noEncrypt/{fileRowId}")
    public void showImageInterfaceNoEncrypt(
            @PathVariable String fileRowId,
            HttpServletResponse response)
	{
        try {
            CustomContractFileRelation contractFile = customContractRelationService.getById(fileRowId);

			// contractFile.getServerFilePath() 其实就是获取文件在服务器上的地址的
            fileUtil.getFileNoDownloadByFileRowId(contractFile.getServerFilePath(), response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


	public void getFileNoDownloadByFileRowId(String fileServerPath , HttpServletResponse response) throws IOException{
		getFileNotDown(fileServerPath, response);
	}



	public void getFileNotDown(String downLoadPath, HttpServletResponse response) throws IOException {
		FileInputStream fis = null;
		OutputStream os = null;
		try {
			String fileType = getFileType(downLoadPath);
			response.setCharacterEncoding("UTF-8");
			if ("pdf".equals(fileType)){
				response.setContentType("application/pdf;charset=utf-8");
			}else if ("xlsx".equals(fileType)){
				response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
			}else if ("docx".equals(fileType)){
				response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
			}
			File targetFile = new File(downLoadPath);
			fis = new FileInputStream(targetFile);

			os = response.getOutputStream();
			response.setHeader("Content-Length", String.valueOf(targetFile.length()));

			int count;
			byte[] buffer = new byte[1024 * 8];
			while ((count = fis.read(buffer)) != -1) {
				os.write(buffer, 0, count);
				os.flush();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fis.close();
				os.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

2.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值