c# - 使用 Interop 传递 SharePoint 凭据以访问 Excel 文件?

标签 c# sharepoint excel-interop

string url = HttpUtility.HtmlAttributeEncode("https://site.sharepoint.com/sites/Project/Shared%20Documents/ExcelSheet.xlsx");

        Excel.Application xlApp = new Excel.Application();
        Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(url):

这会提示我输入电子邮件(用户 ID)和密码,我知道我可以传递密码,但如何获取其中的电子邮件(用户 ID)。

我还保存了 SharpePoint 凭据,我最初尝试使用 SharepointClient,但就能够下载该文件而言,我不知道如何将其转换为 Excel 工作簿以循环访问单元格。

ClientContext context = new ClientContext("https://site.sharepoint.com/sites/Project/"):          
SecureString passWord = new SecureString();

 context.Credentials = new SharePointOnlineCredentials(password)      

干杯!

最佳答案

而不是 Excel Interop我建议使用Excel Services REST API它允许读取 Excel 数据,而不依赖于外部或第三方库。

示例

以下示例演示如何从 Financial Sample.xlsx 读取工作簿数据存储在 SharePoint Online Documents

中的示例 excel 文件
var credentials = GetCredentials(userName, password);
var client = new ExcelClient(webUrl, credentials);
var data = client.ReadTable("Shared Documents/Financial Sample.xlsx", "Sheet1","A1", "P500");
JObject table = JObject.Parse(data);
int idx = 0;
foreach(var row in table["rows"])
{
     if(idx == 0)
     {
        //skip header
     }
     else
     {
        //get cell values
        var segment = row[0]["v"] as JValue;
        var country = row[1]["v"] as JValue;
        Console.WriteLine("Segment: {0}, Country: {1}", segment.Value,country.Value);
     }
     idx++;
}

哪里

WebClient class用于使用 Excel Services REST

public class ExcelClient : WebClient
{

    public ExcelClient(string webUrl, ICredentials credentials)
    {
        BaseAddress = webUrl;
        Credentials = credentials;
        Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f");
    }

    public string ReadTable(string fileUrl, string sheetName, string cellStart,string cellEnd, string format="json")
    {

        var endpointUrl = BaseAddress + string.Format("/_vti_bin/ExcelRest.aspx/{0}/Model/Ranges('{1}!{2}|{3}')?$format={4}", fileUrl,sheetName,cellStart,cellEnd,format);
        return DownloadString(endpointUrl);
    }

}

SharePointOnlineCredentials class通过用户凭据访问 SharePoint Online 资源

static ICredentials GetCredentials(string userName, string password)
{
    var securePassword = new SecureString();
    foreach (var c in password)
    {
        securePassword.AppendChar(c);
    }
    return new SharePointOnlineCredentials(userName, securePassword);
}

结果

enter image description here

enter image description here

引用文献

关于c# - 使用 Interop 传递 SharePoint 凭据以访问 Excel 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52584741/

相关文章:

c# - 在 ASP.NET Core 中使用 reloadOnChange 重新加载选项

ios - Office 365 SharePoint 列表通知新项目

sharepoint - 工作流程: How to Create/Update an Item if it Exists or Does Not

excel - 如何让数据透视表列字段的成员按自然顺序而不是按字母顺序显示?

c# - 如何检查数组中对元素的数量?

c# - 如果字符串为空,则抛出异常的一种衬垫

Excel C API 等效于 C# 中的 Interop Range.Value

c# - 循环遍历范围对象excel C#

c# - iPhone 文件不持久

visual-studio - 缺少 “Deploy” - 按钮 Visual Studio 2012