从 Excel 加载项进行 ajax 调用

Make ajax call from Excel Add-in

是否可以从 Excel 2013 加载项进行 ajax 调用? 如果不是,那么为 Excel 创建可以执行 ajax 调用的任务窗格的最佳方法是什么?

是的,我实际上已经完全按照您的意愿做了。这里有一些提示

  1. excel 表单操作不是线程安全的。确保在单击将执行 http 请求的按钮后禁用所有表单控件 btnDownload.Enabled = false; 并在执行完成后重新启用它。
  2. 使用 `HttpClient` 的实例来执行您的所有请求以获取 json
  3. 从我的错误中吸取教训。硬着头皮使用 This json library 满足您的所有 json 需求。如果您需要任何动态的东西,标准的 .net json 提供程序是不够的。

我的代码在执行操作时通常采用以下格式。

// click handler for vsto excel add-in
private async void btnDownload_Click(object sender, RibbonControlEventArgs e)
{
    btnDownload.Enabled = false;
    using (var client = new HttpClient())
    {
        var resp = await client.GetAsync("http://somepath.com/data.json");
        var statusCode = (int) resp.StatusCode;
        if (statusCode == 200)
        {
            var json = await resp.Content.ReadAsStringAsync();
            var jobj = JObject.Parse(json); // from the library I mention.
            // lookup docs on how to manipulate jobj
            // then make calls to excel api to affect spreadsheet from the json.
        }
    }
    btnDownload.Enabled = true;
}