Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have written a procedure that will open a xls from a local disc, refresh the data in it and then save it again. This works fine.

The problem occurs when I replace the filename to point to a SharePoint site. It opens the file fine. Refreshes the file, but when it trys to save the file it throws an exception with the message "Cannot save as that name. Document was opened as read-only.". If I try and save the file with a different filename then it works fine.

Does anybody know what I am missing? I think it must have somethoing to do with how I am opening the file. Is there another way that I can force the opening of the file in a read/write manner?

    private static void RefreshExcelDocument(string filename)
    {
        var xls = new Microsoft.Office.Interop.Excel.Application();
        xls.Visible = true;
        xls.DisplayAlerts = false;
        var workbook = xls.Workbooks.Open(Filename: filename, IgnoreReadOnlyRecommended: true, ReadOnly: false);
        try
        {
            // Refresh the data from data connections
            workbook.RefreshAll();
            // Wait for the refresh occurs - *wish there was a better way than this.
            System.Threading.Thread.Sleep(5000);
            // Save the workbook back again
            workbook.SaveAs(Filename: filename);  // This is when the Exception is thrown
            // Close the workbook
            workbook.Close(SaveChanges: false);
        }
        catch (Exception ex)
        {
            //Exception message is "Cannot save as that name. Document was opened as read-only."
        }
        finally
        {

            xls.Application.Quit();
            xls = null;
        }
    }

Many thanks in advance for suggestions.

Jonathan

like image 658
Jonathan Stanton Avatar asked Nov 09 '10 09:11

Jonathan Stanton


People also ask

Can we read Excel File in C?

Solution 1: Search for a library that can enable you reading . xlsx file. Solution 2: Write your own parser for . xlsx format. .xlsx is an open format. .xlsx is an ooxml format, so it is essentially a zip formatted compressed file.

How do I load a workbook in C#?

You need to have installed Microsoft Visual Studio Tools for Office (VSTO). VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development. After that create a generic . NET project and add a reference to Microsoft.


1 Answers

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.

like image 113
Alex Angas Avatar answered Sep 22 '22 08:09

Alex Angas