2010-11-09 38 views
6

我已經編寫了一個過程,它將從本地磁盤打開xls,刷新其中的數據並再次保存。這工作正常。以讀/寫模式在C#中從SharePoint網站以編程方式打開xls電子表格

當我將文件名替換爲指向SharePoint網站時,會發生此問題。它打開文件很好。刷新文件,但當它試圖保存文件時,它會拋出一個異常,並顯示消息「不能保存爲該名稱,文檔以只讀方式打開」。 如果我嘗試使用不同的文件名保存文件,那麼它工作正常。

有人知道我失蹤了嗎?我認爲它必須與我如何打開文件有關。有沒有另一種方式可以強制以讀/寫方式打開文件?

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; 
     } 
    } 

非常感謝您的建議。

Jonathan

回答

7

不幸的是,您無法使用Excel API直接保存到SharePoint。這就是文件以只讀方式打開的原因 - 這是不允許的。

好消息是,這是可能的,但你必須通過網絡請求提交表格。更好的消息是有sample code on MSDN!特別通知PublishWorkbook方法通過Web請求發送Excel文件的本地拷貝到服務器:

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(); 
    } 
} 

的示例代碼描述了一個場景爲2007年版本的這些產品,但其他版本應該在行爲同樣的方式。

0

失敗示例的文件名是什麼樣的?數據庫中是否存儲有用於SharePoint的文檔?還是我讓你的問題錯了?否則,我可以想象,您嘗試存儲的文件是由操作系統寫保護的,無法修改。

+0

該文檔的URL看起來像「https://domainname/sites/sitename/Shared%20Documents/filename.xls」。它可以打開此文件並將文件保存到像這樣的網址,但無法保存到同一文件。您不應直接引用數據庫中的文檔,因爲Microsoft可能會更改過夜存儲文檔的方法。 – 2010-11-09 09:49:03

相關問題