读取存储在SharePoint文档库中的Excel文件

时间:2013-01-24 08:12:00

标签: c# sharepoint-2010

我有一个存储在SharePoint文档库中的Excel文件。我需要读取此excel文件并从文件路径

以编程方式获取数据

例如: SharePoint站点:http:// servername:1000

Excel文件路径:http:// servername:1000 / ExcelDocs // ExcelFile.xlsx

正如我们所见,我有excel文件存储在SharePoint文档库中的路径。我需要从这个文件中获取数据。有什么想法吗?

由于

2 个答案:

答案 0 :(得分:5)

实际上,只使用SharePoint功能,您可以在不涉及任何第三方组件的情况下阅读Excel文件内容。

该解决方案演示了如何使用SharePoint REST服务来读取Excel数据。关于这种方法的另一点,因为根本没有没有依赖于SharePoint库,服务器端和客户端组件都没有被引用。

  

先决条件:必须配置Excel Services service application

准备Excel数据

假设以下excel文件

enter image description here

包含工作簿中的以下项目:

在将文件上传到SharePoint库之前,请转到File -> Browse View Options -> choose Items in the Workbook,如下所示。然后保存文件并将其上载到SharePoint Documents库中。

enter image description here

如何通过Excel Services 2010 REST API

读取Excel数据

以下示例演示了如何使用Excel Services 2010 REST API读取 Excel表格内容

using System;
using System.Net;

namespace SharePoint.Client.Office
{
    public class ExcelClient : IDisposable
    {

        public ExcelClient(Uri webUri, ICredentials credentials)
        {
            WebUri = webUri;
            _client = new WebClient {Credentials = credentials};
        }


        public string ReadTable(string libraryName,string fileName, string tableName,string formatType)
        {
            var endpointUrl = string.Format("{0}/_vti_bin/ExcelRest.aspx/{1}/{2}/Model/Tables('{3}')?$format={4}", WebUri,libraryName,fileName, tableName, formatType);
            return _client.DownloadString(endpointUrl);
        }


        public void Dispose()
        {
            _client.Dispose();
            GC.SuppressFinalize(this);
        }

        public Uri WebUri { get; private set; }

        private readonly WebClient _client;

    }
}

<强>用法

该示例演示了如何使用JSON格式读取表内容:

var credentials = new NetworkCredential(userName,password,domain);  
var client = new ExcelClient(webUri, credentials);
var tableData = client.ReadTable("Documents","ciscoexpo.xlsx", "CiscoSalesTable","html");

参考

答案 1 :(得分:1)

您可以从SPFile对象获取二进制数据,然后在第三方库ClosedXML

中打开它
SPFile file = web.GetFile("http://servername:1000/ExcelDocs//ExcelFile.xlsx");
Stream dataStream = file.OpenBinaryStream();
XLWorkbook workbook = new XLWorkbook(dataStream);

或者您可以使用OpenXML,即Microsoft SDK。

SPFile file = web.GetFile("http://servername:1000/ExcelDocs//ExcelFile.xlsx");
Stream dataStream = file.OpenBinaryStream();
SpreadsheetDocument document = SpreadsheetDocument.Open(dataStream, false);
Workbook workbook = document.WorkbookPart.Workbook;

以下是使用OpenXML的example