Jon*_*ton 6 c# excel sharepoint wss
我编写了一个程序,它将从本地光盘打开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;
}
}
Run Code Online (Sandbox Code Playgroud)
非常感谢您的建议.
乔纳森
遗憾的是,您无法使用Excel API直接保存到SharePoint.这就是为什么文件以只读方式打开的原因 - 这是不允许的.
好消息是它有可能,但你必须通过网络请求提交表格.更好的消息是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();
}
}
Run Code Online (Sandbox Code Playgroud)
示例代码描述了这些产品的2007版本的方案,但其他版本的行为方式应该相同.
归档时间: |
|
查看次数: |
5803 次 |
最近记录: |