以读/写模式从SharePoint站点以C#编程方式打开xls电子表格

我已经写了一个程序,将从本地光盘打开xls,刷新其中的数据,然后再次保存。 这工作正常。

当我replace文件名指向SharePoint网站时,会发生问题。 它打开文件正常。 刷新文件,但是当它试图保存文件时,它会抛出一个exception,并显示消息“不能保存为该名称,文档以只读方式打开”。 如果我尝试使用不同的文件名保存文件,那么它工作正常。

有人知道我错过了什么吗? 我认为这应该与我如何打开文件有关。 有没有另外一种方法可以强制以读/写方式打开文件?

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

提前非常感谢您的build议。

乔纳森

不幸的是,您无法使用Excel API直接保存到SharePoint。 这就是为什么文件被打开为只读 – 这是不允许的。

好消息是,这是可能的,但你必须通过networking请求提交表格。 更好的消息是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版本的情况,但其他版本的行为应该是相同的。

什么是失败的例子的文件名看起来像? SharePoint中存储的文档是否存储在数据库中? 还是我得到你的问题错了? 否则,我可以想象你试图存储的文件是由操作系统写保护的,不能被修改。