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):
这会提示我输入电子邮件(用户名)和密码,我知道我可以传递密码,但是如何在其中获取电子邮件(用户名)。
我还保存了SharpePoint凭据,我尝试使用SharepointClient进行尝试,但是我可以下载该文件,但我不知道如何将其转换为Excel工作簿以遍历单元格。 / p>
ClientContext context = new ClientContext("https://site.sharepoint.com/sites/Project/"):
SecureString passWord = new SecureString();
context.Credentials = new SharePointOnlineCredentials(password)
干杯!
答案 0 :(得分:1)
我建议使用Excel Interop而不是Excel Services REST API,它可以读取excel数据,而无需依赖外部或第三方库。
示例
以下示例演示了如何从存储在SharePoint Online Documents
库中的Financial Sample.xlsx
示例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);
}
结果
参考