Opening a xls spreadsheet programatically in C# from a SharePoint site in Read / Write mode

耗尽温柔 提交于 2019-12-05 06:57:30
Alex Angas

Unfortunately you can't save directly to SharePoint using the Excel API. That's why the file is being opened as read only - it's not allowed.

The good news is that it is possible, but you have to submit the form via a web request. Even better news is that there is sample code on MSDN! In particular notice the PublishWorkbook method that sends a local copy of the Excel file to the server via a web request:

static void PublishWorkbook(string LocalPath, string SharePointPath)
{
    WebResponse response = null;

    try
    {
        // Create a PUT Web request to upload the file.
        WebRequest request = WebRequest.Create(SharePointPath);

        request.Credentials = CredentialCache.DefaultCredentials;
        request.Method = "PUT";

        // Allocate a 1K buffer to transfer the file contents.
        // The buffer size can be adjusted as needed depending on
        // the number and size of files being uploaded.
        byte[] buffer = new byte[1024];

        // Write the contents of the local file to the
        // request stream.
        using (Stream stream = request.GetRequestStream())
        using (FileStream fsWorkbook = File.Open(LocalPath,
            FileMode.Open, FileAccess.Read))
        {
            int i = fsWorkbook.Read(buffer, 0, buffer.Length);

            while (i > 0)
            {
                stream.Write(buffer, 0, i);
                i = fsWorkbook.Read(buffer, 0, buffer.Length);
            }
        }

        // Make the PUT request.
        response = request.GetResponse();
    }
    finally
    {
        response.Close();
    }
}

The sample code describes a scenario for the 2007 versions of these products but other versions should behave in the same way.

What does the filename of a failed example looks like? Aren't documents used in SharePoint stored in the database? Or am I getting your problem wrong? Otherwise I could imagine that the file you are trying to store is write protected by the operation system and cannot be modified.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!