我编写了一个程序,它将从本地光盘打开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;
}
}
非常感谢您的建议。
乔纳森
答案 0 :(得分:7)
很遗憾,您无法使用Excel API直接保存到SharePoint。这就是为什么文件以只读方式打开的原因 - 这是不允许的。
好消息是有可能,但您必须通过网络请求提交表单。更好的消息是有sample code on MSDN!特别注意通过Web请求将Excel文件的本地副本发送到服务器的PublishWorkbook
方法:
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版本的方案,但其他版本的行为应该相同。
答案 1 :(得分:0)
失败示例的文件名是什么样的? SharePoint中使用的文档不是存储在数据库中的吗?或者我的问题出错?否则我可以想象你试图存储的文件是由操作系统写保护的,不能被修改。