vue写excel add-in

2,175

vue-excel-addin git地址

项目需求 有空就尝试使用vue去构建一个excel addin
微软太坑爹了,只给了ng react jquery的教程
文档会尝试中英文双语的

使用Vue来构建一个Excel add-in

在这篇文章,你可以看到是如何使用Vue和Excel的JavaScript API来构建一个Excel add-in的

需要

  • 安装Vue-cli
npm install --global vue-cli
npm install -g yo generator-office

生成新的Vue项目

使用vue-cli来搭建脚手架,在命令行输入如下命令: vue init webpack vue-excel-addin

生成manifest文件和加入add-in配置

每个add-in都需要一个manifest文件来配置和定义它的功能

  1. 进入app文件
    cd vue-excel-addin
  2. 使用Yeoman来生成你的add-in的manifest文件, 运行如下命令
    yo office
  • Would you like to create a new subfolder for your project?: No
  • What do you want to name your add-in?: My Office Add-in
  • Which Office client application would you like to support?: Excel
  • Would you like to create a new add-in?: No

生成工具会问你是否需要打开 resource.html.这篇文档无需打开, 当然如果你好奇的话,打开也没关系! 选择 yes 或者 no 让生成工具完成它的工作把!

jpg

如果你被提示要覆盖 package.json, 选择 No (do not overwrite).

  1. 跟着以下的教程来运行你的excel add-in吧
注意,请把manifest的相关端口修改为dev默认的8080以及将根目录的assets移入static并修改相关配置
  1. 编辑package.json 给dev脚本添加--https参数

更新app

  1. 打开index.html, 把以下的<script>标签添加到</head>之前
<script src="https://appsforoffice.microsoft.com/lib/1/hosted/office.js"></script>
  1. 打开src/main.js 将new Vue({ el: '#app', components: {App}, template: '<App/>' })替换成以下
Office.initialize = () => {
  new Vue({
    el: '#app',
    components: {App},
    template: '<App/>'
  })
}
  1. 打开 src/App.vue, 修改为如下
<template>
  <div id="app">
    <div id="content">
      <div id="content-header">
        <div class="padding">
          <h1>Hello world!</h1>
        </div>
      </div>
      <div id="content-main">
        <div class="padding">
          <p>Choose the button below to set the color of the selected range to green.</p>
          <br/>
          <h3>Try it out</h3>
          <button @click="onSetColor">Set color</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'App',
    methods: {
      onSetColor() {
        window.Excel.run(async (context) => {
          const range = context.workbook.getSelectedRange()
          range.format.fill.color = 'green';
          await context.sync()
        })
      }
    }
  }
</script>

<style>
  #content-header {
    background: #2a8dd4;
    color: #fff;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 80px;
    overflow: hidden;
  }

  #content-main {
    background: #fff;
    position: fixed;
    top: 80px;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
  }

  .padding {
    padding: 15px;
  }
</style>

试一下吧

  1. 在命令行输入以下命令
Windows:

npm start

macOs:

npm start

  1. 在Excel中的开始tab, 选择Show Taskpane按钮来打开add-in的task pane

    d

  2. 选择任意一个区域的单元格

  3. 在task pane内, 点击 Set color按钮来将选中区域的颜色转为绿色