You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中实现Excel刷新Web查询时请求用户凭据

在OpenXML生成的Excel Web查询中添加用户认证功能

你可以通过配置WebQueryProperties的关键属性,实现Excel刷新时弹出用户名密码输入框的需求,具体修改如下:

修改Web查询配置

在你的WebQueryProperties实例中添加以下核心属性:

  • CredentialsMethod:设置为3,对应Excel的「提示输入凭据」模式
  • PromptCredentials:设为true,强制Excel在刷新时触发认证窗口
  • 可选SavePassword:若允许用户保存密码则设为true,若需每次刷新都提示则设为false

修改后的完整代码片段

ConnectionsPart connPart = workbook.WorkbookPart.AddNewPart<ConnectionsPart>();
connPart.Connections = new Connections();
var connection1 = new Connection()
{
    Id = 1,
    Name = "Connection1",
    Type = 4, // Web Query
    WebQueryProperties = new WebQueryProperties
    {
        Url = "myurlfordatarefresh",
        CredentialsMethod = 3, // 指定提示用户输入凭据
        PromptCredentials = true,
        SavePassword = false // 不保存密码,每次刷新都触发提示
    }
};

connPart.Connections.Append(connection1);
Sheet sheet = new Sheet() { Id = relationshipId, SheetId = sheetId, Name = "mysheet" };
QueryTablePart qt = sheetPart.AddNewPart<QueryTablePart>();

qt.QueryTable = new QueryTable() { Name = "Connection", ConnectionId = connection1.Id, RefreshOnLoad = true };

DefinedNames definedNames = new DefinedNames();
definedNames.Append(new DefinedName()
{
    Name = "Connection",
    Text = "mysheet!$A$2:$A$2"
});

关键说明

  • 后端API需要支持HTTP基本认证:Excel会将用户输入的用户名和密码以Base64编码形式,放在请求头的Authorization字段中发送
  • 若API使用非基本认证方式(如Bearer Token),原生提示框无法直接适配,需通过VBA宏实现自定义认证逻辑,但会涉及Excel宏权限限制问题

内容的提问来源于stack exchange,提问作者Deepti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 04:52:50