问题
We need to create a c# application that can modify an Excel file in one of our Sharepoint online sites.
For a local file I do like this:
Excel.Application excel_app = new Excel.Application();
excel_app.Visible = true;
Excel.Workbook workbook = excel_app.Workbooks.Open(
<path to excel file>,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
But if I put the url of the Sharepoint Excel file it does not work. Is this feasible, and how?
回答1:
You can download the file, modify it, upload the file and replace it
Here is how to connect to a sharepoint site and upload a file
Use the Microsoft.SharePoint.Client namespace
using SP = Microsoft.SharePoint.Client;
...
using (var context = new SP.ClientContext(new Uri(<YOURSITEURL>))) {
var web = context.Web;
context.Credentials = new NetworkCredential(<NETWORK_USERNAME>, <NETWORK_PASS>, <DOMAIN_NAME>);
context.Load(web);
try
{
context.ExecuteQuery();
} catch (Exception ex) {
}
var file = web.GetFileByServerRelativeUrl(new Uri(<FILE_URL>).AbsolutePath);
context.Load(file);
try
{
context.ExecuteQuery();
file.SaveBinary(new SP.FileSaveBinaryInformation() { Content = Encoding.UTF8.GetBytes(<NEW_FILE>) });
try
{
context.ExecuteQuery();
}
catch (Exception ex)
{
}
}
}
回答2:
To upload a file(excel,word etc) to sharepoint online below is the code: Note: create your project in .net FRAMEWORK(do not do this in .net core) and install the nuget package of Microsoft.SharePointOnline.CSOM
ClientContext ccontext = new ClientContext("<URL>/sites/<foldername>");
var securePassword = GetPasswordAsSecureString("<YOUR PASSWORD>"); // function is below
ccontext.AuthenticationMode = ClientAuthenticationMode.Default;
var onlineCredentials = new SharePointOnlineCredentials("<YOU-EMAIL-ID>", securePassword);
ccontext.Credentials = onlineCredentials;
List lst = ccontext.Web.Lists.GetByTitle("Documents");
var DestSubFolder = "General/Data";
Folder fileFolder = lst.RootFolder;
if (DestSubFolder.Length > 0)
fileFolder = CreateFolderInternal(ccontext.Web, lst.RootFolder, DestSubFolder);
// upload File.
FileCreationInformation newFile = new FileCreationInformation();
byte[] FileContent = System.IO.File.ReadAllBytes("c://Temp/test.txt");
newFile.ContentStream = new MemoryStream(FileContent);
newFile.Url = Path.GetFileName("c://Temp/test.txt");
newFile.Overwrite = true;
fileFolder.Files.Add(newFile);
fileFolder.Update();
ccontext.ExecuteQuery();
private static SecureString GetPasswordAsSecureString(string password)
{
SecureString securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
return securePassword;
}
来源:https://stackoverflow.com/questions/37837675/programmatically-modifying-a-sharepoint-online-excel-file