Excel and web services

Содержание

  1. Excel Services Architecture
  2. Web Front-End Servers and Back-End Application Servers
  3. Excel Web Access
  4. Excel Web Services
  5. User-Defined Functions (UDFs)
  6. ECMAScript (JavaScript, JScript)
  7. REST API
  8. Excel Calculation Services
  9. Load-Balancing
  10. Новые возможности веб-служб Excel
  11. Excel Web Services Enhancements
  12. Новые методы
  13. New Enumerations
  14. New Types
  15. What’s New in Excel Web Services
  16. Excel Web Services Enhancements
  17. New Methods
  18. New Enumerations
  19. New Types
  20. Excel Web Services
  21. In This Section

Excel Services Architecture

Excel Services is part of Microsoft SharePoint Server 2010. Excel Services is built on ASP.NET and SharePoint Foundation technologies. Following are the core components in Excel Services:

Excel Web Access

Excel Web Services

User-defined functions (UDFs)

ECMAScript (JavaScript, JScript)

Representational State Transfer (REST) service

Excel Calculation Services

Microsoft Excel Online, part of Office Online, also supports Excel workbooks in the browser. For more information about Excel Online, see documentation about Office Web Apps.

The Excel Web Access, Excel Web Services, UDFs, JavaScript, the REST service, and Excel Calculation Services components can be divided into two major groups: the components on a front-end server (also known as the «Web front end») and the component on a back-end application server. Components of a Web front end and a back-end application server

Web Front-End Servers and Back-End Application Servers

The Excel Web Access, Excel Web Services, UDFs, JavaScript, the REST service, and Excel Calculation Services components can be divided into components on the Web front-end server and components that live on a back-end application server. The Web front end includes Excel Web Access, JavaScript, the REST service, and Excel Web Services. The Excel Calculation Services component resides on the back-end application server, alongside any UDF assemblies that an administrator has added.

In the simplest configuration in SharePoint Server 2010—that is, a single computer running SharePoint Server 2010 as a stand-alone installation—all five components are installed on the same computer. However, in a typical enterprise environment with a large number of users, the components on the Web front-end server and the components on the back-end application server are on different computers in a farm configuration. It is possible to scale out the Web front-end server independently from the back-end application server. For example, you can have more Web front-end servers or more back-end application servers, depending on your organizational needs.

For information about Excel Services topology, scalability, performance, and security, see the SharePoint Server 2010 documentation on TechNet.

Excel Web Access

Excel Web Access is a viewer page and an Excel Services web part that you can add to any web parts page in SharePoint Server 2010. Excel Web Access renders (in other words, creates the HTML for) live Excel workbooks on a webpage, and enables the user to interact with those workbooks and explore them. Excel Web Access is the visible Excel Services component for the user. You can use Excel Web Access like any other web part in SharePoint Server 2010. Excel Web Access does not require the user to install anything on the client computer.

The Excel Web Access web part properties are also customizable. For more information, see the Microsoft.Office.Excel.Server.WebUI namespace reference documentation.

Excel Web Services

Excel Web Services is the Excel Services component that provides programmatic access to its Web service. You can develop applications that call Excel Web Services to calculate, set, and extract values from workbooks, and to refresh external data connections. By using Excel Web Services, you can incorporate server-side workbook logic into an application, automate the updating of Excel workbooks, and create application-specific user interfaces around server-side Excel calculation.

When you make changes to a workbook—for example, by setting values to a range by using Excel Web Services—the changes to the workbook are preserved only for that session. The changes are not saved or persisted back to the original workbook. When the current workbook session ends (for example, when you call the CloseWorkbook method, or when the session times out), the changes that you made are lost.> If you want to save changes that you make to a workbook, you can use the GetWorkbook method, and then save the workbook. For more information, see Microsoft.Office.Excel.Server.WebServices . You can also open the workbook in edit mode and save the changes.

For more information about Excel Web Services, see Excel Services Development Roadmap.

User-Defined Functions (UDFs)

Excel Services UDFs enable you to use formulas in a cell to call custom functions that are written in managed code and deployed to SharePoint Server 2010. For more information about UDFs in Excel Services, see Understanding Excel Services UDFs.

ECMAScript (JavaScript, JScript)

The JavaScript object model in Excel Services enables developers to customize, automate, and drive the Excel Web Access web part control on a page. By using the JavaScript object model, you can build mashups and other integrated solutions that interact with one or more Excel Web Access web part controls on a page or an iframe with script on the page. It also enables you to add more capabilities to your workbooks and code around them.

For more information about the JavaScript object model in Excel Services, see the Ewa namespace reference documentation.

REST API

The REST API in Excel Services enables you to access workbook parts or elements directly through a URL. The URL contains a «marker» path, which is the entry point to an .aspx page, to the workbook file location, and to the path to the requested element inside the workbook.

The discovery mechanisms built into the Excel Services REST API enables developers and users to explore the content of a workbook manually or programmatically.

For more information about the REST API in Excel Services, see Excel Services REST API.

Excel Calculation Services

The role of Excel Calculation Services is to load workbooks, calculate workbooks, call custom code (UDFs), and refresh external data. It also maintains the session state for interactivity. Excel Calculation Services maintains a session for the duration of interactions with the same workbook by a user or caller. A session is closed when the caller explicitly closes it or when the session times out on the server. Excel Services caches the opened Excel workbooks, calculation states, and external data query results, for improved performance when multiple users access the same set of workbooks.

Load-Balancing

In multiple-server configurations, Excel Services load-balances requests across multiple Excel Calculation Services occurrences in a farm configuration. If your installation includes multiple application servers, Excel Services will balance the load in an attempt to help ensure that no single application server is overloaded by requests.

Administrators can configure the load-balancing behavior.

Источник

Новые возможности веб-служб Excel

This topic lists the new types and members added to Веб-службы Excel.

Excel Web Services Enhancements

Веб-службы Excel is expanded and enhanced in Microsoft SharePoint Server 2010. In SharePoint Server 2010, you can edit and save a workbook programmatically. In addition, the Веб-службы Excel now supports opening workbooks in edit sessions in SharePoint Server 2010. In this scenario, you can use code to edit a workbook at the same time that other users are co-authoring the workbook.

For more information about the Веб-службы Excel API and more detailed remarks about the new methods, enumerations, and types, see Microsoft.Office.Excel.Server.WebServices.

Новые методы

The following are new methods added to Веб-службы Excel, in alphabetical order:

GetChartImageUrl Gets a URL value to the chart or PivotChart image file in a workbook.

GetPublishedItemNames Gets a list of published items in a workbook.

GetSheetNames Gets a list of all of the sheet names present in a workbook.

OpenWorkbookForEditing Opens a workbook for editing.

SaveWorkbook Saves a workbook in the original format (.xlsx, .xlsb, .xlsm).

SaveWorkbookCopy Saves a workbook by using a different file name and/or saves a workbook to a different SharePoint document library.

SetCalculationOptions Changes the calculation mode setting for workbooks.

SetParameters Sets multiple published parameters with a single Web Service call.

You can now set formulas by using the set value methods.

Dynamic ranges are supported in Веб-службы Excel in SharePoint Server 2010.

New Enumerations

The following are new enumerations added to Веб-службы Excel, in alphabetical order:

ItemType Indicates the types of the returned items.

SheetType Indicates the types of the returned sheets.

SheetVisibility Indicates whether the returned sheets are visible.

SaveOptions Specifies whether to overwrite an existing, unlocked file.

WorkbookCalculation Defines the calculation mode setting for a workbook.

New Types

The following are new types added to Веб-службы Excel, in alphabetical order:

ParameterInfo Gets or sets the name and values of a parameter.

SheetInfo Contains information about a sheet in a workbook.

Size Defines the width and height of the chart image

WorkbookItem Represents named items in the workbook.

Источник

What’s New in Excel Web Services

This topic lists the new types and members added to Excel Web Services.

Excel Web Services Enhancements

Excel Web Services is expanded and enhanced in Microsoft SharePoint Server 2010. In SharePoint Server 2010, you can edit and save a workbook programmatically. In addition, the Excel Web Services now supports opening workbooks in edit sessions in SharePoint Server 2010. In this scenario, you can use code to edit a workbook at the same time that other users are co-authoring the workbook.

For more information about the Excel Web Services API and more detailed remarks about the new methods, enumerations, and types, see Microsoft.Office.Excel.Server.WebServices.

New Methods

The following are new methods added to Excel Web Services, in alphabetical order:

GetChartImageUrl Gets a URL value to the chart or PivotChart image file in a workbook.

GetPublishedItemNames Gets a list of published items in a workbook.

GetSheetNames Gets a list of all of the sheet names present in a workbook.

OpenWorkbookForEditing Opens a workbook for editing.

SaveWorkbook Saves a workbook in the original format (.xlsx, .xlsb, .xlsm).

SaveWorkbookCopy Saves a workbook by using a different file name and/or saves a workbook to a different SharePoint document library.

SetCalculationOptions Changes the calculation mode setting for workbooks.

SetParameters Sets multiple published parameters with a single Web Service call.

You can now set formulas by using the set value methods.

Dynamic ranges are supported in Excel Web Services in SharePoint Server 2010.

New Enumerations

The following are new enumerations added to Excel Web Services, in alphabetical order:

ItemType Indicates the types of the returned items.

SheetType Indicates the types of the returned sheets.

SheetVisibility Indicates whether the returned sheets are visible.

SaveOptions Specifies whether to overwrite an existing, unlocked file.

WorkbookCalculation Defines the calculation mode setting for a workbook.

New Types

The following are new types added to Excel Web Services, in alphabetical order:

ParameterInfo Gets or sets the name and values of a parameter.

SheetInfo Contains information about a sheet in a workbook.

Size Defines the width and height of the chart image

WorkbookItem Represents named items in the workbook.

Источник

Excel Web Services

Applies to: SharePoint Server 2010

This section contains information about Excel Web Services and explains how to use it to develop custom applications.

In This Section

What’s New in Excel Web Services
Learn about the new types and members added to Excel Web Services in Microsoft SharePoint Server 2010.

Accessing the SOAP API
Learn how to call the Web service by referencing the Excel Web Services Web Services Description Language (WSDL).

Loop-Back SOAP Calls and Direct Linking
Learn when to link to Microsoft.Office.Excel.Server.WebServices.dll locally.

Walkthrough: Developing a Custom Application Using Excel Web Services
Get step-by-step instructions about how to create a Web service client application that accesses Excel Web Services.

Excel Services Error Codes
Read about the error codes for Excel Web Services alerts and the associated messages, explanations, and resolutions.

How to: Set Credentials
Learn how to set credentials for your users so that they can call Excel Web Services by using your custom applications.

How to: Get an Entire Workbook or a Snapshot
Learn how to get an entire workbook, a snapshot of the file, or a snapshot of the viewable sheets or objects in the file by using Excel Web Services.

How to: Save a Workbook
Learn about using the various libraries in the Microsoft .NET Framework to save a workbook.

How to: Get Values from Ranges
See examples of the four methods for getting values from an Excel workbook.

How to: Set Values of Ranges
Learn how to use the four methods for setting values in an Excel workbook.

How to: Specify a Range Address and Sheet Name
Learn how to specify range addresses by using range coordinates, named ranges, rows, and columns. Also learn how to specify a sheet name, and about the relationship between a sheet name and a range address.

How to: Use the CloseWorkbook Method Call Asynchronously
Find out how to close a workbook asynchronously to save some operation time.

How to: Refresh Data
Learn how you can use the Refresh method to retrieve updated data from external data sources for an open workbook.

How to: Use the SubCode Property to Capture Error Codes
Get examples that show how to capture Excel Services error codes when using SOAP and when using direct linking.

Источник

excel webservice function

The Excel WEBSERVICE and Excel FILTERXML Worksheet functions can be used to pull Internet data from a URL into a cell in a Excel spreadsheet. While the first pulls raw HTML data the second allows you to filter XML formats.

Excel up till now has been mostly an offline application. Although, you can use VBA, PowerQuery or other similar data tools in Excel to gain access to Internet and Online data sets these could not have been easily used with the help of Third Party AddIns such as my Scrape HTML AddIn. With the introduction of the WEBSERVICE function we gain immediate and easy access to any REST WebAPI.

In today’s post I will show you several examples of how to use these functions in practice. And how to extract data from an XML REST WebApi.

How to use the Excel WEBSERVICE function

The WEBSERVICE function downloads the HTTP response of the provided URL.
excel webservice function
Try running the Excel WEBSERVICE function on Google:

=WEBSERVICE("https://www.google.com")

What do you get? If all goes well you should get the HTML response for the Google Web Page.
Now past the above formula to cell A1 and the below to cell A2:

=MID(A1;FIND("<title>";A1)+LEN("<title>");FIND("</title>";A1)-FIND("<title>";A1)-LEN("<title>"))

The result of this Worksheet Excel Formula should be:

Google

Using FILTERXML in tandem with WEBSERVICE

Another function introduced in Excel 2013 is the FILTERXML function. It is designed to work in tandem with the Excel WEBSERVICE function.

What does the FILTERXML function do?

The Excel FILTERXML Worksheet function parses a XML string (string containing XML document) and returns a single element (node or attribute) provided by a XPath.
excel filterxml
Lots of odd words there right? So let us start breaking it down. XML is markup language for encoding documents. As a matter of fact HTML is based on XML and share a lot of similarities. Unfortunately for us HTML does not need often have to be as strictly parsed/validated as an XML does. Although some HTML could pass as XML files – in fact many Websites don’t validate as XML.

Now what is XPath? XPath is a query language for selecting XML elements such as nodes and attributes. XPath works for XML and HTML.

How to use the FILTERXML function

Now that we know what the FILTERXML functions let’s use it on a simple XML file. W3Schools fortunately has a lot of simple XML examples – let us use a simple XML Food Menu:

Example: WEBSERVICE and FILTERXML function

filterxml and webservice example 1

Example: WEBSERVICE and FILTERXML result

filterxml and webservice example 2

Explanation

xml exampleNow to explain what happens above. The XML file includes a couple of nodes – each one nested within the previous one. We start with node which hosts nodes. Each food node represents a single item in the menu. A food node contains , and node – which describe each menu item.

Now the FILTERXML functions used the following XPath: //food/name. This translates to: take the first food tag and return the contents of it name node.

Scraping a whole XML document

Now the example above is fine when you need just a single node from your XML document URL. What if you want to scrape the whole contents of that XML? Thankfully we can combine the WEBSERVICE and FILTERXML functions with Array Formulas.

In the example below I will show you how to acquire all the names of the food items in the menu. You can use a similar technique to get other items.

Input the FILTERXML formula

Input the FILTERXML formula as shown below:

=FILTERXML(B2;"//food/name")

filterxml and webservice example 4

Drag the formula down

Drag the formula down to row 8:
filterxml and webservice example 5

Hit CTRL+SHIFT+ENTER

Hit the following key combo to create and Array Formula: CTRL+SHIFT+ENTER.
That is it. Now in each row you should see the name of a food item from the menu.

Don’t like using Array Functions? You can also use the XPath node index instead:

=FILTERXML(B2;"//food[2]/name")

will return the name of the second food menu item. To replicate this across all items use this example:

=FILTERXML(B$2;"//food[" & (ROW()-ROW(B$4)+1) &"]/name")

Provide you entered this function in cell B2, simply drag it down – the items should automatically complete.

WEBSERVICE functions Restrictions

Now the WEBSERVICE function unfortunately has several restrictions that will cause the function to return a #VALUE! error instead of the string:

  • If you don’t have a working Internet connection (or you are working with a proxy server)
  • Incorrect arguments or URL address
  • If HTTP result is not valid or contains more than the cell limit of 32767 characters
  • URL is a string that contains more than the 2048 characters that are allowed for a GET HTTP request
  • Protocols that aren’t supported, such as ftp:// or file://

Excel WEBSERVICE summary

The WEBSERVICE and FILTERXML functions are a great step forward to enabling access to Internet resources. These still have unfortunately a lot of limits. Especially when most websites have HTML files that exceed the 32727 character limit and often don’t parse as XML files.

This is where my VBA Web Scraping Kit fills the gap together with my Scrape HTML AddIn. The Kit has all the Web Scraping scenarios I consider possible in Excel where as the Scrape HTML AddIn extends a little the constrains of the WEBSERVICE and the FILTERXML functions

Want to learn Web Scraping?

Not satisfied? Want to know more about Web Scraping in Excel using VBA? Read my zero-to-hero Web Scraping Tutorial.

Excel Web Services(Позже указаноEWS)ПолностьюExcel ServicesВнешний интерфейс(Может обратиться к моей предыдущей статье)Отказ Это обеспечивает развитиеExcelИнтерфейс. Как видно из имени,EWSТакже принадлежитWebServiceОдин, поэтому мы можем использовать обычныеWebServiceЭто использует это. ЗвонитьEWSВо-первых, мы должны знать его адрес, в зависимости отMOSSпараметр. еслиMOSSИмяServerName,ЗатемEWSАдрес: http://<server name>/_vti_bin/ExcelService.asmx .Войдите в браузерEWSВы увидите рисунок ниже после адреса:

<shapetype id=»_x0000_t75″ stroked=»f» filled=»f» path=»[email protected]@[email protected]@[email protected]@[email protected]@5xe» o:preferrelative=»t» o:spt=»75″ coordsize=»21600,21600″><stroke joinstyle=»miter»><formulas><f eqn=»if lineDrawn pixelLineWidth 0″><f eqn=»sum @0 1 0″><f eqn=»sum 0 0 @1″><f eqn=»prod @2 1 2″><f eqn=»prod @3 21600 pixelWidth»><f eqn=»prod @3 21600 pixelHeight»><f eqn=»sum @0 0 1″><f eqn=»prod @6 1 2″><f eqn=»prod @7 21600 pixelWidth»><f eqn=»sum @8 21600 0″><f eqn=»prod @7 21600 pixelHeight»><f eqn=»sum @10 21600 0″></f><path o:connecttype=»rect» gradientshapeok=»t» o:extrusionok=»f»><lock aspectratio=»t» v:ext=»edit»></lock><shape id=»Picture_x0020_1″ style=»VISIBILITY: visible; WIDTH: 248.25pt; HEIGHT: 558pt» type=»#_x0000_t75″ o:spid=»_x0000_i1026″><imagedata o:title=»webService» src=»file:///C:%5CDOCUME%7E1%5Clancer%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_image001.png»></imagedata></shape></path></f></f></f></f></f></f></f></f></f></f></f></formulas></stroke></shapetype>

Нечего сказать, теперь иди на сегодняшнюю тему, пройду одинПрограмма показывает, как использоватьEWS.

Эта программа все еще будет использоватьПредыдущая статьяВошелExcelДокументация. Прочитайте сначала после работы программыSharePoint ServerВверхExcelРабота худой,A1кB3Содержание ячейки отображается к интерфейсу программы; Вы также можете изменить контент в текстовом поле, затем нажмите кнопку «Расчет».,Соответствующий тег отобразит результат обновления; или нажмите Сохранить, поставьте серверExcelРабота хранится локально.
<shape id=»Picture_x0020_2″ style=»VISIBILITY: visible; WIDTH: 225pt; HEIGHT: 225pt» type=»#_x0000_t75″ o:spid=»_x0000_i1025″><imagedata o:title=»applicaiton_excelWebService» src=»file:///C:%5CDOCUME%7E1%5Clancer%5CLOCALS%7E1%5CTemp%5Cmsohtmlclip1%5C01%5Cclip_image002.png»></imagedata></shape>

Теперь создайте приложение. Сначала установите имяExcelWebServciceизWindowsПрименение, будетEWSЦитируется в программу, измените пространство имен наExcelWebServcice

Вы можете использовать эту услугу после добавления ссылки.

Вся программа разделена на3раздел:1, Значение 2Назначение 3,спасти

<!—[if !supportLists]—>1. <!—[endif]—>Ценить

воляEWSПосле добавления к проекту вы можете увидетьExcelWebServiceПространство имен появилось под пространством именExcelServiceкласс. Вы можете завершить взаимодействие с сервером, используя его.

Прежде всего, экземпляр

ExcelService es=new ExcelService();

НазыватьExcelServiceПрежде чем у вас есть указанные учетные данные (Credential), В противном случае приложение бросит исключение. Учетные данные могут быть учетными данными по умолчанию или использовать указанное имя пользователя./Пароль учетных данных,Здесь мы используем учетные данные по умолчанию. Разница между ними будет обсуждаться позже.

es.Credentials = System.Net.CredentialCache.DefaultCredentials;

es.Credentials = new System.Net.NetworkCredential(«userName», «password»,»domain»);

Мы выполним после установки учетных данныхOpenWorkbookФункция этого метода объявляется следующим образом:

string ExcelService.OpenWorkbook(string workbookPath, string cultrueInfo,string cultrueInfo,string out status)

OpenWorkbookДля открытияExcelworkbookPathУказывает адрес файла на сервере.cultureInfo,cultureInfoРегиональная информация, здесь мы заполняем”zh-cn”(Представляющий китайский язык)Отказ Последний параметр немного особенный, этоStatusМассив типов для хранения сообщений об ошибках. ИсполнительныйExcelServiceОшибки могут возникнуть, когда метод. Серьезные ошибки могут привести к сбою программы, а небольшие ошибки не влияют на работу программы, а сообщение об ошибке будет сохранена.StatusРяд типов типов. Стоит отметить, чтоExcelServiceВсе методы в классе участвуют в этом параметре.

Последнее введение в возвращаемое значение этого метода: исполнениеOpenworkbookЗадний,Excel Calculation ServerСеанс будет сгенерирован. Номер сеанса хранитсяOpenWorkbookВозвращаемое значение внутри.

Успешно реализоватьOpenWorkbookКак только вы можетеExcelЦенить. Нам нужно от документацииsheet1Первая клетка взята, то естьA1Значение в клетках. можешь использоватьGetCellA1метод.

object GetCellA1(string sessionID,string sheetName,string rangeName,bool formatted,out Status[] status)

GetCellA1Метод требует количества сеансов, зависит от того, какой сеансExcelПринять ценность работы; параметрыsheetNameКакой из них определяетсяsheetПринять значение; параметрrangeNameОпределить, какая ячейка взята из значения;formattedУказывает, сохраняется ли формат при значениях;

Увидев это здесь, у вас могут быть несколько вопросов:GetCellсGetCellA1Какие отличия там?A1Что это означает?

ФактическиGetCellA1В методеA1представительExcelПравила именования. ТыExcelВ одном входе в ячейке”=A1”или же” =Sheet1!$A$1” Указывая на то, что ячейка цитируетсяA1Значение ячейки, только это.

Excel Calculation ServiceТакже поддерживает другое правило: принять систему координат/Ценить. Это правило соответствуетGetCellметод. Но теперь система начала системы координаты0НетExcelсередина1Отказ Таким образом, наш код должен быть следующим:

Es.GetCell(workbookPath,”sheet1”,0,0,true,out status);

После того, как стоимость завершена, вам нужно отключить работу.,Выпустить ресурсы, уменьшить нагрузку на сервер

es.CloseWorkbook(sessionID)

Раздел стоимости был представлен, посмотрите на полный код:

string workbookPath = @»http://vistaserver/dc/ExcelServiceTest/test.xlsx»;

string cultrueInfo = «zh-cn»;

Status[] status;

/// <summary>

/// На сервереexcelЗначение в документе

/// </summary>

void GetValueFromServer()

{

ExcelService es = new ExcelService();

es.Credentials = System.Net.CredentialCache.DefaultCredentials;

string sessionID = es.OpenWorkbook(workbookPath, cultrueInfo, cultrueInfo, out status);

A1Field.Text = es.GetCellA1(sessionID, «sheet1», «A1», true, out status).ToString();

A2Field.Text = es.GetCellA1(sessionID, «sheet1», «A2», true, out status).ToString();

A3Field.Text = es.GetCellA1(sessionID, «sheet1», «A3», true, out status).ToString();

number1.Text = es.GetCellA1(sessionID, «sheet1», «B1», true, out status).ToString();

number2.Text = es.GetCellA1(sessionID, «sheet1», «B2», true, out status).ToString();

result.Text = es.GetCellA1(sessionID, «sheet1», «B3», true, out status).ToString();

es.CloseWorkbook(sessionID);

}

<!—[if !supportLists]—>2. <!—[endif]—>Ценить:

ExcelServiceСпособ ячейки в классеSetCellA1(а такжеSetCellКак использовать можно будет ссылатьсяGetCell). Функция этого метода объявляется следующим образом

Status status=SetCellA1(string sessionID,string sheetName,string rangeName,object cellValue)

Посмотрите на полный код раздела расчета:

ExcelService es = new ExcelService();

es.Credentials = System.Net.CredentialCache.DefaultCredentials;

string sessionID = es.OpenWorkbook(workbookPath, cultrueInfo, cultrueInfo, out status);

es.SetCellA1(sessionID, «sheet1», «B1», number1.Text);

es.SetCellA1(sessionID, «sheet1», «B2», number2.Text);

result.Text = es.GetCellA1(sessionID, «sheet1», «B3», true, out status);

<!—[if !supportLists]—>3. <!—[endif]—>спасти

Вы можете заметить, что код разделения «Назначение» отсутствует.CloseWorkbookметод. Причины могут быть связаны с вышеуказанными:Excel Calculation ServiceОтвечает за поддержание сеанса, чтобы можно было использовать несколько пользователейExcel Calculation ServiceНе будет взаимодействовать друг с другом. Таким образом, закрывая работу, заставляя закрыть сеанс, прежде чем на сессииExcelПроизведенная операция также будет потерянаСледовательно, операция сохранения должна быть завершена до выключения сеанса.

Посмотри на это сейчасExcelМетод работы:

byte[] GetWorkbook(string sessionID,WorkbookType workbookType,out Status[] status)

GetWorkbookДобраться от сторон сервераExcelРаботать тонко, будетbyteМассив возвращен. Этот метод включает в себя3Параметры. Я хочу все параметрыsessionIDсstatusИспользование более знакомо, здесь я сосредоточусь на следующемWrokbookTypeИмея в виду.

WorkbookTypeТип перечисления:

public enum WorkbookType

{

FullWorkbook,

FullSnapshot,

PublishedItemsSnapshot,

}

FullWorkbookСамая мощная функция, вы можете получить полную работу на сервере (всеsheet

FullSnapshotсFullWorkbookПохоже, вы также можете получить полную работу тонкого снимка

PublishedItemsSnapshotСамая слабая функция, может получить только снимкость работы, которую автор позволяет просматривать(Помните, что последняя упомянутая статья”ExcelServiceВариант?)

Увидев это, у всех может быть немного сомнений: просто настроитьFullWorkbookили жеFullSnapshotВы можете получить полную работу, автор выпускаетсяExcelЭто не используется при работе? О, это на самом деле не тот (или любой случай) можно использовать.FullWorkbook/FullSnapshotиз. Помните «учетные данные», которые я упомянул раньше? Могут быть использованы только учетные данные, которые предлагают достаточные разрешения.

Позвольте мне поговорить о разнице между «полной работой» и «Снимок». Снимок можно понимать как подмножество первых. Тем не менее, снимок не может использовать формулу, введенную в тонкими работами, и не может использовать внешние соединения данных.

OkGetWorkbookВведениеЗаканчиватьBi, посмотрите на программный код.

byte[] content = es.GetWorkbook(sessionID, WorkbookType.PublishedItemsSnapshot, out status);

es.CloseWorkbook(sessionID);

FileStream fs = new FileStream(«c:\test.xlsx», FileMode.Create);

fs.Write(content, 0, content.Length);

fs.Flush();

fs.Close();

Теперь общая функция программы была завершена. Надеюсь, что это может помочь нам.

Я только ввел это.Excel Web ServiceОсновной метод использования, я хочу добавить больше функций в программе, полностью представить его.Excel Web ServiceМетод. Но я действительно не знаю, как это выразить :( Я познакомим вас в статье.user-defined functions (UDFs). Спасибо снова для всех, чтобы просмотреть.

by stswordman

In this article, we will explaining how to implement a web service call from Microsoft Excel. The prerequisite for this? We must have web service toolkit installed.

EXCEL and the Web Services Toolkit

First, the Microsoft Excel environment has to be prepared. For use with Office 2003, Microsoft delivers the Web Services Toolkit 2.01 for download at:
http://www.microsoft.com/downloads/details.aspx?FamilyID=fa36018a-e1cf-48a3-9b35-169d819ecf18&DisplayLang=en

After the installation, the Web Services plug-in can be found in the Excel VB editor under Extras > Web Service References.
Excel is now ready to import WSDL files for the automatic creation of classes and data types to call the corresponding web services.

Creating the Web Service in SAP

The next step is to generate a web service from the SAP RFC function module and t expose it as WSDL file.
For example: convert RFC function module Z_ BAPI_XXXX_CREATEFROMDATA (any RFC enables function module) into a web service.

  • In SE37, go to Utilities->Create Web Service and follow the simple steps.

  • Go to transaction SOAMANGER and generate the WSDL.

Building the EXCEL Application

Now everything is prepared for the EXCEL application.

  • From the VB editor, choose «Web Service Reference» and mark the «Web Service URL» checkbox.

  • Type the full address of the WSDL file (e.g. C:Z_XYZ.xml).

  • A search result should appear (as shown in below snapshot).
    If the WSDL file is correctly spelled and no search result appears, then it means WSDL file may be incorrect. One reason may be that in SAP, the input and output types are different (e.g. upper case for input fields, lower case for output fields).

  • Check the service and press the «add» button. The toolkit will parse the file and create type definitions and classes in the VB editor.

Wizard Results

After the upload of the WSDL file, the toolkit has added new classes of different types to the EXCEL project.
Some classes represent the table structures. In the example, the interface consists of the tables and other simple import structures leading to the structure classes (for the businesspartner tables e.g.:struc_BAPIBUS1037VBKAKOMCR).

Two other classes provide the objects for working with the web service. The method for calling the service in the example is in a class called

clsws_zcreatesalesactivity               

And here the method for calling the service is implemented:

Public Sub wsm_Z_XXXX_CREATEFROMDATA (ByRef ar_BUSINESSPARTNER As

Variant, ByRef ar_GENERALDATA As Variant, ByRef ar_RETURN As Variant,

ByVal obj_SENDER As struct_BAPISENDER, ByVal str_TESTRUN As String)

Note that all table parameters are of type «variant», simple structures are of respective type «struc_xxx» and simple variables are of type «string».
In case of individual other applications, the classes and type definitions need to be checked: All tables and structure parameters from the function interface should appear as class modules named struc_xxx, including the type definitions for all fields. If not, check for restricted words in the data definitions of the WSDL file.

These fields are converted by the Web Services Toolkit in Excel according to

Public FROM_DATE As date

To avoid deserialization failed errors in the Web Service call, all «date» fields must be redefined to «string».

Public FROM_DATE As String

Calling the Service

To call the web service, an object needs to be created:

Dim SalesActivityWS As New clsws_zCreateSalesActivityS

Then all input tables need to be filled. This can be achieved for all tables as follows. First declare the table variables as ?Variant?. For example, for the businesspartners:

Dim ar_BUSINESSPARTNER as variant

Additionally, a variable of type struc_BAPIBUS1037VBKAKOMCR is needed to fill the input data. To account for more than one entry, the variable is defined as array.

Dim _StrucBusinesspartner(2) as struc_BAPIBUS1037VBKAKOMCR

Now the structure _StrucBusinesspartner can be filled from a corresponding EXCEL table or by use of VB input forms according to the needs. Finally, the input variables are transferred:

ar_BUSINESSPARTNER = _StrucBusinesspartner

And the service is called.

Call SalesActivityWS. wsm_Z_XXXX_CREATEFROMDATA ( ar_BUSINESSPARTNER,

ar_GENERALDATA, ar_RETURN, obj_SENDER, str_TESTRUN)

After the execution of the service, all ar_RETURN fields can be evaluated.

Possible Errors

If the deserialization error occurs, check again for remaining fields of type date or lower case field names.

Another error might read «too many open connections». This means the service could not log on to SAP. Check the user name and password provided in transaction SICF. 

Сценариииспользования Excel Services

   Просмотр электронныхтаблиц через браузер

   Создание компонентов дляанализа данных

   Использование вклиентских приложениях логики, встроенной в таблицы Excel

Расширениефункциональности Excel Services: пользовательские функции

Чем не является ExcelServices

Ограничения ExcelServices

Обзорархитектуры Excel Services

Microsoft Office 2007 будет включать новый продукт — Microsoft Office 2007 Excel Services. В задачу этого серверного компонента входит реализация ряда сценариев, которые мы рассмотрим в данном документе. Мы также расскажем о механизмах расширения Excel Services за счет создания пользовательских функций и об ограничениях в текущей версии Excel Services, а завершим наш обзор кратким рассмотрением его архитектуры, безопасности и масштабируемости.

Сценарии использования Excel Services

Три основных сценария применения сервисов Excel выглядят следующим образом:

• просмотр электронных таблиц через браузер;

• создание компонентов для анализа данных (Business Intelligence Dashboard);

• использование логики, встроенной в таблицы Excel, в клиентских приложениях.

Просмотр электронных таблиц через браузер

В настоящее время существует несколько способов обмена электронными таблицами для предоставления доступа к расположенным в них данным — отсылка таблиц по электронной почте, публикация в файловых каталогах общего доступа, сохранение таблицы в виде Web-страницы и т.п. Для некоторого класса электронных таблиц (таблиц, содержащих конфиденциальную бизнес-информацию, уникальную бизнес-логику, таблиц, основанных на большом количестве вычислений, а также для таблиц, которые предназначены для клиентов или партнеров) многие из перечисленных способов обмена не подходят. Например, внесенные в таблицы изменения порождают многочисленные версии приблизительно одних и тех же данных; возникают сложности с защитой информации, поставляемой в рамках электронной таблицы; помимо этого сложные таблицы, наполненные комплексными вычислениями, не всегда удобно пересылать по электронной почте.

Большинство из перечисленных проблем можно решить, используя Excel Services: при помощи Excel 2007 автор может опубликовать созданную им электронную таблицу в библиотеке документов SharePoint и затем разрешить доступ к серверной версии этой таблицы через Web-браузер. Когда пользователь обращается к такой таблице, службы Excel Services загружают таблицу, при необходимости обновляют внутренние данные, производят необходимые вычисления и генерируют HTML/DHTML-поток, отсылаемый в Web-браузер клиента. На клиентском компьютере для просмотра таблиц не требуется установки ни клиентской версии Excel 2007, ни даже каких-либо компонентов ActiveX. Пользователи всегда получают самую последнюю версию электронной таблицы, а у автора появляется возможность ограничить доступ к определенным книгам внутри таблицы, закрыть некоторые диапазоны и т.п. Более того, пользователи не видят формул, использовавшихся для вычисления значений ячеек. За счет того что Excel Services базируется на технологиях SharePoint, у авторов появляется возможность обеспечения безопасности, контроля за доступом, аудита, применения встроенных средств документооборота, версионности и т.п.

Существует два способа публикации электронных таблиц на сервере. Можно использовать команды Save или Save As для сохранения таблиц в библиотеке документов SharePoint: для этого необходимо указать имя сервера и имя файла — либо в UNC-, либо в HTTP-формате. Второй способ, появившийся в Excel 2007 впервые, представляет собой команду Publish To Office Server. Выполнение этой команды не только публикует электронную таблицу на сервере, но и позволяет задать ряд параметров, которые будут использоваться при обращении к серверной таблице.

Диалоговая панель Publish to Office Server выглядит так, как представлено на нижеследующем рисунке:

Публикация таблицы на сервере

По умолчанию опция Open the workbook in my browser включена — сразу же после публикации таблицы вы увидите ее содержимое в вашем браузере.

Как мы уже отмечали, при публикации на сервере с помощью команды Publish To Office Server можно задать несколько опций. К таким опциям, в частности, относятся область видимости и параметры, передаваемые электронной таблице при ее открытии.

В Excel 2007 можно задать три области видимости: вся таблица (значение по умолчанию), подмножество книг и набор именованных элементов (диапазоны, графики, таблицы, сводные таблицы, сводные графики).

Задание области видимости

Поскольку пользователи, просматривающие электронные таблицы в браузере, не могут изменять их содержимое, то для поддержки ряда сценариев в Excel Services реализована возможность задания параметров. Параметры электронной таблицы позволяют авторам выделять некоторые ячейки таблицы и делать их редактируемыми в браузере. Для этих целей в Excel Services предоставляется специальная панель задач.

Панель задач для редактирования ячеек

После того как значения будут изменены, электронная таблица выполнит пересчет и пользователь увидит новые значения. Важно отметить, что не все ячейки могут быть доступны через параметры. В текущей версии Excel Services существуют следующие ограничения: параметр не может указывать на диапазон ячеек, ячейка не должна содержать формулу, ячейка должна относиться только к обычной таблице — не поддерживаются ячейки сводных таблиц, графиков и т.п., ячейка должна быть поименована.

Для превращения ячейки в параметр используется диалоговая панель публикации таблицы. Вкладка Parameters служит для добавления, редактирования и удаления параметров.

Вкладка Parameters

Нажатие кнопки Add приводит к появлению списка доступных ячеек, соответствующих заданному критерию. Также существует объектная модель, поддерживающая превращение ячейки в параметр.

Завершая рассмотрение данной темы, следует отметить, что существует возможность установки значений ячеек, которые не видны пользователю, — это позволяет, например, представить в браузере пустую таблицу и предоставить клиенту возможность ее заполнения.

Метод

Описание

GetApiVersion

Возвращает версию программных интерфейсов Web-сервисов

sessionId = OpenWorkbook

Открывает серверную сессию — необходимо указать местоположение таблицы и ряд других параметров. Метод возвращает идентификатор сессии (sessionId)

GetSessionInformation

Возвращает ряд свойств серверной сессии

SetCell

Задает значение указанной ячейки таблицы. Существует две версии данного метода. Первая использует адрес ячейки, например “B52”, или именованный диапазон, например “Interest”; вторая версия использует числовые координаты, что бывает удобно в тех случаях, когда обращение к ячейкам происходит в цикле

SetRange

Задает значение указанного диапазона ячеек. Поддерживаются те же самые варианты адресации, что и для метода SetCell

Refresh

Считывает данные из внешних источников и обновляет значения в соответствующих ячейках электронной таблицы, например в ячейках сводной таблицы или в результирующих формулах OLAP-куба

Calculate

Пересчитывает формулы в указанном диапазоне или во всей таблице. Следует использовать в тех случаях, когда автоматический пересчет на уровне таблицы отключен

CalculateWorkbook

Пересчитывает всю таблицу, используя один из следующих методов вычислений:

Recalculate — пересчитывает только формулы, зависимости которых изменились

CalculateFull — пересчитывает все формулы, независимо от состояния зависимостей

GetCell

Возвращает значение указанной ячейки. Результат работы метода — отформатированные строчные значения или бинарные значения

GetRange

Возвращает набор значений, хранящихся в указанном диапазоне ячеек

GetWorkbook

Возвращает всю пересчитанную таблицу в виде байтового массива

CancelRequest

Если приложение выполняет сессию Excel Web Services в отдельном потоке и требуется завершить серверный запрос, например долготекущие вычисления, используйте данный метод

CloseWorkbook

Заставляет сервер закрыть электронную таблицу, которая была открыта в данной сессии, а сервер высвобождает все ресурсы, выделенные на поддержание контекста текущей сессии

Создание компонентов для анализа данных

Вторым типовым сценарием использования Excel Services является предоставление данных, хранимых в электронных таблицах, для анализа. На следующем рисунке показана панель (dashboard), созданная средствами Excel 2007, Excel Services и SharePoint Portal Server без единой строки кода.

Панель анализа данных

Все интерактивные средства, ассоциируемые со сводными таблицами, доступны пользователям непосредственно из браузера. Отметим, что средства анализа, реализованные в Excel 2007/Excel Services, содержат возможность интеграции с SQL Server 2005 и доступ (через специальный набор формул) к средствам создания отчетов — SQL Server Reporting Services.

Использование в клиентских приложениях логики, встроенной в таблицы Excel

Третий типовой сценарий применения Excel Services — это повторное использование бизнес-логики, включенной в таблицы Excel из внешних приложений. Помимо интерфейса на уровне браузера, Excel Services поддерживает доступ к электронным таблицам через Web-сервисы. Это означает, что та же самая электронная таблица, опубликованная на сервере и доступная через браузер, может быть доступна и из приложения, использующего Web-сервисы, предоставляемые Excel Services. Такое приложение может изменять значения в таблице, производить вычисления, извлекать всю или часть таблицы и т.п.

Приведем несколько примеров функций, реализованных в Web-сервисах Excel Services.

Вот пример кода, использующего некоторые из перечисленных методов Web-сервиса Excel Services:

// Создать экземпляр прокси и аутентифицироваться

ExcelService ws = new ExcelService();

ws.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Открыть «книгу» Excel

Status[] status = null;

string sessionId = null;

sessionId = ws.OpenWorkbook(textBoxURL.Text, “en-US”, “en-US”, out status);

// Задать значения ячеек

status = ws.SetCell(sessionId, “Mortgage Calculator”, “CustomerName”, textBoxCustomerName.Text);

status = ws.SetCell(sessionId, “Mortgage Calculator”, “MortageAmount”, textBoxAmount.Text);

status = ws.SetCell(sessionId, “Mortgage Calculator”, “InterestRate”, textBoxInterest.Text);

status = ws.SetCell(sessionId, “Mortgage Calculator”, “MortgageLength”, textBoxLength.Text);

// Выполнить вычисления и получить результат

status = ws.CalculateWorkbook(sessionId, CalculateType.Recalculate);

object result = null;

result = ws.GetCell(sessionId, “Mortgage Calculator”, “Payment”, true, out status);

// Показать результат и закрыть «книгу»

if (result != null)

MessageBox.Show(“You pay” + result.ToString());

status = ws.CloseWorkbook(SessionId);

Таким образом, инвестиции в бизнес-логику, реализованную внутри электронных таблиц, могут быть сохранены и такая логика может быть повторно использована в других приложениях без необходимости переписывания уже существующего кода.

Расширение функциональности Excel Services: пользовательские функции

В Excel Services поддерживается возможность расширения функциональности за счет создания собственных функций (User Defined Functions, UDF). Такие функции могут использоваться в формулах для вычисления значений ячеек электронной таблицы и таким образом расширять набор функций, входящих в состав Excel Services.

UDF в Excel Services — это код, написанный на управляемом коде и сохраненный в виде стандартных сборок .NET 2.0. Сборка должна содержать как минимум один класс, помеченный атрибутом [UdfClass], и как минимум один метод, помеченный атрибутом [UdfMethod]. UDF может выполнять любые действия (в реальности это зависит от настроек Code Access Security), включая вызов внешнего неуправляемого кода, Web-сервисов и т.п.

При добавлении UDF к Excel Services вы расширяете набор существующих функций Excel — эта операция схожа с функциональностью XLL и Automation Addins в Excel.

Первый шаг при создании UDF — это добавление к проекту библиотеки классов ссылки на сборку Microsoft.Office.Excel.Server.Udfs.dll, которая, в частности, определяет необходимые для реализации UDF атрибуты.

Затем мы создаем класс, который будет содержать метод(ы) нашей функции, и указываем соответствующие атрибуты. После компиляции нашего проекта мы получаем сборку, содержащую UDF, которую мы должны подключить к Excel Services. Для этого мы переходим на страницу администрирования сервисов — User Defined Functions — и нажимаем кнопку Add User-Defined Function Assembly.

Диалоговая панель
Add User-Defined Function Assembly

После этого в диалоговой панели заполняем соответствующие поля: местоположение сборки, статус сборки (локальная или относящаяся к глобальному кэшу сборок), активизация сборки и ее описание. После этих манипуляций сборка, содержащая UDF, готова к использованию.

Чем не является Excel Services

При рассмотрении Excel Services важно понимать, чем не являются серверные компоненты Excel 2007. Ниже приведен список функциональности, не реализованной в первой версии серверных компонентов:

  • средство создания электронных таблиц — с помощью браузера нельзя создавать или редактировать электронные таблицы — для этих целей служит программный продукт Excel 2007, распространяемый как отдельно, так и в составе различных изданий Microsoft Office 2007;
  • средство многопользовательской работы с таблицами — в данной версии Excel Services каждый пользователь работает с таблицей в своей собственной сессии. Сервер открывает таблицу в режиме «только чтение» и каждый пользователь получает экземпляр таблицы, сохраненный в памяти сессии. Таблица загружается в память сервера один раз, но все манипуляции, например установка фильтров, сохраняются в отдельной сессии и используются для перерисовки таблицы в браузере конкретного пользователя;
  • распределение нагрузки по серверам при проведении вычислений — Excel Services поддерживает механизмы распределения нагрузки при вычислениях и позволяет производить вычисления в более чем одной таблице (каждый запрос выполняется в отдельном потоке), но в данной версии сервисов не поддерживается разбиение одной таблицы с комплексными вычислениями на несколько серверов. Текущий дизайн сервисов рассчитан на масштабирование при большом числе таблиц и увеличении числа запросов к серверу.

Ограничения Excel Services

В первой версии серверных компонентов  — Excel Services — существует ряд ограничений, которые мы кратко здесь рассмотрим.

Говоря о возможных ограничениях в Excel Services, следует понимать, что Excel 2007 является мощным, комплексным приложением, предназначенным для табличной обработки данных и их анализа, и в первой версии серверных компонентов вряд ли может быть в полном объеме реализована функциональность продукта класса Excel 2007. В первую очередь набор функциональности, реализованной в Excel Services, был направлен на поддержку рассмотренных выше сценариев. В следующих версиях серверных компонентов планируется расширить функциональность.

Рассмотрим некоторые аспекты поддержки функциональности Excel 2007 в Excel Services:

  • загрузка файлов — Excel Services не загружает все файлы Excel. В некоторых случаях, когда Excel Services не поддерживает определенную функциональность Excel 2007, не загружается тот или иной файл. Так, Excel Services не поддерживает выполнение VBA-кода;
  • просмотр файлов — в ряде случаев Excel Services не может отобразить объект из электронной таблицы таким образом, как Excel 2007. К указанным объектам, в частности, могут относиться расширения деловой графики в Excel 2007: при отображении через Excel Services графики могут не иметь всех новых визуальных эффектов;
  • взаимодействие с файлами — некоторые интерактивные функции не поддерживаются на уровне браузера. Например, пользователи лишены возможности добавления или перераспределения полей в сводных таблицах при работе с электронными таблицами, отображаемыми в браузере;
  • создание файлов — как уже было отмечено, этот сценарий не входит в число поддерживаемых в данной версии Excel Services. Например, нельзя вставить график или изменить формулу в электронной таблице, открытой средствами Excel Services.

После перечисления основных ограничений рассмотрим их более подробно. Ниже показаны характеристики электронных таблиц, которые не могут быть загружены средствами Excel Services:

  • таблицы с кодом — к таким таблицам относятся таблицы с VBA-макросами, компонентами форм, компонентами инструментальных панелей, панелями MS 5.0 Dialogs и XML-таблицы;
  • таблицы, защищенные средствами IRM;
  • таблицы, содержащие компоненты ActiveX;
  • таблицы со встроенными SmartTags;
  • сводные таблицы, основанные на диапазонах множественной консолидации (multiple consolidation);
  • таблицы с внешними ссылками (ссылки на другие таблицы);
  • таблицы, сохраненные в режиме Formula View;
  • таблицы с расширенным использованием XML (XML Expansion Pack);
  • таблицы, содержащие XML Maps;
  • таблицы со средствами визуализации данных;
  • таблицы, содержащие Query Tables, SharePoint Lists, Web Queries и Text Queries;
  • таблицы со ссылочными компонентами (reference add-ins);
  • таблицы, использующие функцию выполнения в реальном времени (RTD);
  • таблицы с защитой самих таблиц и «книг»;
  • таблицы со встроенной графикой, имеющие фоновые изображения на уровне ячеек или таблиц, использующие AutoShapes и WordArt;
  • таблицы, содержащие рукописные аннотации (Ink Annotations);
  • таблицы с диаграммами;
  • таблицы с DDE-связями.

Самый простой способ определить, будет ли таблица открываться средствами Excel Services, — это использовать описанную функцию просмотра в браузере непосредственно после публикации таблицы на сервере. В том случае, если таблица содержит неподдерживаемые данной версией Excel Services функции, вы получите сообщение об ошибке, представленной на рисунке ниже.

Сообщение об ошибке при попытке открыть таблицу средствами Excel Services

Некоторые элементы таблиц не могут быть отображены средствами Excel Services. К таким элементам, в частности, относятся:

  • панели — Split and Freeze Panes;
  • верхние и нижние заголовки;
  • просмотр в режиме Page Layout;
  • шаблоны заполнения ячеек (Cell patterns);
  • средства масштабирования (Zoom);
  • свойства членов Analysis Services, отображаемые в подсказках (tooltips);
  • некоторые варианты форматирования ячеек, а именно диагональные рамки, а также типы рамок, не поддерживаемые на уровне HTML.

К следующей группе относится функциональность Excel 2007 с ограниченными элементами интерактивности при отображении средствами Excel Services. К такой функциональности относятся:

  • графики по сводным таблицам (PivotCharts) — такие графики не будут интерактивными при отображении в браузере, то есть у вас не будет возможности непосредственно задать фильтр для графика, но если обратиться к сводной таблице, служащей источником данных для графика, последний изменится соответствующим образом;
  • сводные таблицы — поддерживается сортировка, фильтрация, раскрытие и закрытие регионов данных для сводных таблиц, отображаемых в браузере, но пользователям будут недоступны функции drill-through, использование служб SQL Server Analysis Services, добавление и удаление полей или их перемещение;
  • функция GoTo — в браузере пользователи могут использовать либо режим Named Object View, либо предоставляемые элементы навигации для перемещения по электронной таблице. Функции GoTo не поддерживаются;
  • увеличение и уменьшение изображения — функции Minimize и Maximize не поддерживаются;
  • переключение в режим Page Layout View, служащий для упрощения печати таблиц в Excel 2007, не поддерживается в браузере;
  • Goal Seek, Scenario Manager, аудит формул, изменение режима вычислений и окно Watch не поддерживаются.

Что касается создания и редактирования таблиц, то, как уже отмечалось, этот сценарий не являлся ключевым в первой версии Excel Services. Перечисленные здесь функции не поддерживаются в серверных компонентах Excel 2007:

  • вставка новой книги;
  • вставка объекта;
  • создание таблицы;
  • вставка сводной таблицы;
  • вставка сводного графика;
  • редактирование формул;
  • вставка данных в ячейки (кроме рассмотренных выше параметризованных ячеек);
  • задание имен;
  • изменение форматирования ячеек;
  • изменение правил и условий форматирования;
  • группировка и отмена группировки — имеется возможность использования групп, заданных средствами Excel 2007;
  • задание консолидированных диапазонов;
  • преобразование текста в колонки.

В Excel Services поддерживается рендеринг графиков, созданных средствами Excel 2007, но следует ожидать некоторых визуальных различий в ряде типов графиков — например не поддерживаются отсечки, тени, отражения и некоторые другие новые расширенные графические функции, появившиеся в Excel 2007.

Выше мы упоминали, что в Excel Services не поддерживается загрузка электронных таблиц, содержащих VBA-код. В Excel Services поддерживаются таблицы, содержащие пользовательские функции на управляемом коде. Вместо дополнений, которые не поддерживаются, можно использовать функции-переходники.

Обзор архитектуры Excel Services

Завершим наше обсуждение сервисов Excel Services кратким рассмотрением архитектуры серверных компонентов. Как уже отмечалось, Excel Services построен на технологиях SharePoint Portal Server. Excel Services состоит из трех основных компонентов:

  • сервис вычислений — Excel Calculation Service;
  • сервис доступа через Web — Excel Web Access;
  • сервис поддержки Web-сервисов — Excel Web Service.

Взаимодействие этих сервисов отражено на представленной диаграмме.

Кратко опишем назначение этих компонентов.

Excel Web Access — представляет собой компонент Web-part в SharePoint, задачей которого является отрисовка (генерация HTML) книги Excel на Web-страницу. Для конечных пользователей, обращающихся к Excel Services, это самый видимый компонент из всего набора сервисов.

Excel Web Services — обеспечивает программный доступ к Excel Services. Представляет собой Web-сервис, расположенный в SharePoint. Методы этого Web-сервиса могут использоваться для разработки приложений, применяющих вычисления, реализованные на основе Excel Services, и для автоматизации обновлений электронных таблиц.

Архитектура Excel Services

Excel Calculation Service — компонент, загружающий электронную таблицу, выполняющий вычисления, обновляющий внешние данные и отвечающий за поддержание состояния сессии.

Помимо перечисленных компонентов, в Excel Services входит прокси-уровень, обеспечивающий коммуникации между компонентами, доступными через Web, и сервером приложений в многосерверных конфигурациях. Также к задачам данного компонента относится обеспечение балансирования нагрузки в тех случаях, когда задействуется более одного сервера приложений.

Модель безопасности, используемая в Excel Services, базируется на инфраструктуре, предоставляемой SharePoint. Excel Services применяет SharePoint для аутентификации, авторизации, а также для аудита выполняемых операций.

Excel Services оптимизирован для сценариев, в которых ряд пользователей обращается к одной и той же электронной таблице. Оптимизация достигается за счет использования различных механизмов кэширования — как для электронных таблиц, так и для применяемых ими источников данных.

Масштабирование Excel Services достигается за счет добавления дополнительных процессоров или памяти на сервере, где выполняются соответствующие сервисы. Excel Services поддерживает конфигурации с несколькими процессорами, равномерно распределяя запросы между ними, а также конфигурации с 64-битными процессорами. В ряде случаев возможен различный подход к вопросам масштабирования сервера приложений и Web-компонентов. Например, если снижается производительность при отрисовке электронных таблиц средствами Excel Web Access, то необходимо увеличить мощность сервера, где выполняются Web-компоненты, а в случае потери производительности при вычислениях следует повысить мощность сервера приложений.

КомпьютерПресс 8’2006

  • Download source files — 30.4 Kb

Introduction

Web Services are reusable applications that expose an interface that can be accessed over the internet. Web services use XML to provide a platform and language independent implementation of distributed application services and information.

Web services allow us to utilize the services provided by the other organizations. We can consume the web services not only from applications developed using various programming languages but also from Microsoft office tools like Access, Excel, and Word etc. In this article we will explore how we can access a web service from Microsoft Excel using Microsoft Office XP Web Services Toolkit 2.0, which simplifies the process of accessing and utilizing an XML webservice.

Details

 Sample screenshot

The example includes a webservice, which returns 5 countries and their capitals. Capitals.xls has 2 buttons. When a user clicks on the display button, Capitals.xls sheet accesses the web service and displays the data provided by the webservice. Clicking on the clear button clears the data from the XL sheet.

Sample screenshot

Now lets see how we can develop this application. Lets start by creating an excel sheet. Drag and drop a button from the visual basic toolbox. (You can get the VB toolbox from the View menu). Now to add a reference to the web service . For this we will use the VB editor (Alt-F11). From the tools menu bar add the reference of Microsoft Soap tool kit. Now lets add the web service reference. For this click on the web reference in the tools menu of the VB editor. You can either search for a web service or if you know the URL of a web service u can directly add it. Now you are ready to access the web service. We can do this by creating an object of the web service class and displaying the result in the excel sheet.

Dim module As clsws_Service1
Dim value As String
Dim data() As String
Dim range1 As Range
Dim range2 As Range
Dim j As Integer
Set module = New clsws_Service1
value = module.wsm_getCapitals()
data = Split(value)
j = 0
Application.ActiveSheet.Range("A4").Activate
Set range1 = Range(Range("A4"), Range("A22"))
For Each range2 In range1
    If j < 9 Then
     range2.Offset(0, 3).value = data(j)
     range2.Offset(0, 4).value = data(j + 1)
     j = j + 2
   End If
Next range2

Working on .NET for last 6 years. Currently working for TCS.

The Microsoft Excel WEBSERVICE function retrieves data from a URL into a single cell within an Excel worksheet. In this article we describe how to use WEBSERVICE to retrieve weather forecast and historical weather data directly into Excel without the need for macros or scripts. However, is it always the best way to work with weather data web services in Excel? Read on to find out!

How does the Excel WEBSERVICE function work?

The WEBSERVICE function is very easy to construct:

=WEBSERVICE(url)

Given a URL, the WEBSERVICE function will retrieve the data for the URL and populate that data into the Excel cell as piece of text. From the Microsoft documentation, a fictitious example would be as follows

=WEBSERVICE(“http://mywebservice.com/serviceEndpoint?searchString=Excel”)

Once the function executes, the data in the cell is available for normal text manipulation using Excel functions.

How to use the Excel WEBSERVICE to retrieve weather data

To retrieve weather data, we first need a web service to retrieve the weather data. We will be using the Timeline Weather API as it includes weather forecast and historical weather data. The Weather API also provides a number of options to manipulate and filter the results which makes it easy to show using the WEBSERVICE function.

If you want to follow along, you can sign up for a free account that will allow you to retrieve 1000 free weather data results every day.

Here’s a simple URL web service the retrieves the weather forecast for the next 15 days:

https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY?unitGroup=us&contentType=csv&key=YOUR_API_KEY

Note the ‘contentType=csv’ parameter – this tells the web service to return the weather data as comma separated values rather than the default JSON format.

If we put this URL in the browser, we can see that we have a table of weather forecast data:

We can put the data into our Excel worksheet using the WEBSERVICE function:

=WEBSERVICE("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY?unitGroup=us&include=days&contentType=csv&key=YOUR_API_KEY")

All this data gets put into Excel as a single cell so the results are a little tricky to read:

This is because the data is large and the CSV formatting isn’t automatically handled by Excel.

How to use the WEBSERVICE function results

As we’ve seen, the WEBSERVICE function can easily retrieve weather data from a Weather API URL. So far the results have been a little hard to understand so now we’ll turn the raw data into something useful.

There are two approaches to this simplification. First we will reduce the amount of information returned from web service call itself. Reducing the amount of data will make our processing easier, faster and will avoid any risk of hitting the Excel cell limit (approximately 32000 characters).

The following request uses the ‘elements’ parameter of the Weather API to reduce the data from the request to the date, maximum temperature and minimum temperature:

https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY?unitGroup=us&include=days&contentType=csv&key=YOUR_API_KEY&elements=datetime,tempmax,tempmin

We can make things even easier by eliminating the headers and targeting the high temperature for a single day:

https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY/2021-05-31?unitGroup=us&include=days&contentType=csv&key=YOUR_API_KEY&elements=tempmax&options=noheaders

Note how we added the date parameter of 31st May 2021. If this is in the future, the query will look up the forecasted high temperature for that date. If this is the past, then the result will be the actual observed high temperature for that date.

This request doesn’t need any kind of processing. It is simply the high temperature for a single date. We can use multiple cells and string concatenation to create a simple weather forecast.

Given a column which includes the date, the request to look up the high temperature for a high temperature is constructed using concatenation:

=CONCAT("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY/",TEXT(A5,"yyyy-mm-dd"),"?unitGroup=us&include=days&contentType=csv&key=YOUR_API_KEY&elements=tempmax&options=noheaders")

Note how the date of the URL is dynamic inserted by formatting the date value found in cell A5

We can surround this with the webservice call to retrieve the data:

=WEBSERVICE(CONCAT("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY/",TEXT(A5,"yyyy-mm-dd"),"?unitGroup=us&include=days&contentType=csv&key=YOUR_API_KEY &elements=tempmax&options=noheaders"))

If we use a table of dates, we can then create a small weather forecast table in Excel:

How to process more complex WEBSERVICE results

In the above example, we generated a simple weather forecast table using multiple functions. We were requesting the weather data using multiple WESERVICE calls – one for each cell. Is there way to request the data just once and the use Excel to process the data?

There are three ways to parse complex result of a web service in Excel:

  1. Use text manipulation functions of Excel to parse the result of the Web Service call directly within the worksheet.
  2. Use VBA macros to parse the result.
  3. Use Web Query connector (which in turn uses PowerQuery to load and parse the data)

Using text manipulation functions of Excel

In the above example, we used a separate WEBSERVICE function to retrieve the data for the high and low temperatures. Let’s see if we can combine these into one:

The web service call is:

=WEBSERVICE(CONCAT("https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/New%20York%20City%2CNY/",TEXT(A5,"yyyy-mm-dd"),"?unitGroup=us&include=days&contentType=csv&key=YOUR_API_KEY&elements=tempmax,tempmin&options=noheaders"))

We now have an cell with a concatenated value resembling “70,58” representing 70 for the forecast high temperature and 58 for the forecast low temperature. To isolate the high and low temperatures we can use a little formula to split the text around the “,” character.

Let’s assume that the above WEBSERVICE is placed in cell B12. We can then use Excel text functions to split up the value of cell B12 .

The left hand side is the high temperature:

=LEFT(B12,FIND(",",B12)-1)

This says “extract the left characters of cell B12 up to, but not including, the first “,” character (the -1 will exclude the “,” character).

The right hand side is the low temperature:

=RIGHT(B12,LEN(B12) - FIND(",",B12))

This says “extract the right characters after the “,”. As the FIND function starts from the left we take the overall length and subtract the result of the FIND to find the start of the low temperature.

Using VBA macros to parse the query results

Using Excel functions to parse the result of the WEBSERVICE function can get a little difficult. Excel has additional tools to manipulated CSV and JSON data. The first is to write a custom VBA script to parse the incoming data.

Web Query Connector & PowerQuery

The next option is to use a ‘Get & Transform Data’ request from the Excel Data menu. Get & Transform Data requests construct a PowerQuery script to retrieve and then transform the data.

PowerQuery is a scripting language of sorts that is built into Excel which includes rich ability to import and manipulate data from web services before populating the result data into an Excel sheet.

The learning curve to using PowerQuery query can be quite steep however importing well defined CSV data such as the Weather API data described here is a simple case. If you would like more information on how to load weather data into Excel using PowerQuery, please see our additional articles.

To WEBSERVICE or PowerQuery?

The Excel WEBSERVICE function is an easy-to-use way to retrieve weather data. This makes the function the easiest way to retrieve simple weather data values into Excel from a Weather API. You can retrieve the high temperature for a day or hour in a single, simple Excel formula.

However WEBSERVICE does not include any way to process the weather data results. If you need to retrieve a long, multiple column weather data result in JSON or CSV format, WEBSERVICE may not the right choice for you. In those cases, PowerQuery is exactly designed for your needs.

Questions or need help?

If you have a question or need help, please post on our actively monitored forum for the fastest replies. You can also contact us via our support site or drop us an email at support@visualcrossing.com.

If your spreadsheet needs to access constantly updated data, or if you need to access services hosted on another computer, Excel’s Web Services support will enable you to get connected.

SOAP-based Web Services have been a key part of Microsoft’s plans for .NET, as well as a common feature of toolkits from other vendors. SOAP (the acronym doesn’t mean anything) is a protocol that uses XML to transmit information between systems. In the case you’ll explore here, it’s used to call procedures and return values. A companion specification, Web Service Definition Language (WSDL), describes Web Services so that applications can connect to them easily. Microsoft’s Web Services Reference Tool can take a WSDL file and generate VBA code your application can use to access SOAP-based web services.

This tutorial uses Excel features that are available only in Excel XP and Excel 2003 on Windows. Earlier versions of Excel do not support this, and neither do current or announced Macintosh versions of Excel.

Making this work requires downloading the Office Web Services Toolkit. As its location has changed a few times, it’s easiest to go to http://www.microsoft.com/downloads/search.aspx and search for «Office Web Services Toolkit». Separate versions are available for Office XP and Office 2003. You’ll need to install this toolkit, using the directions that come with it, before proceeding with this tutorial.

Once you’ve installed the toolkit, you can start connecting your spreadsheet to web services. To get to the Web Service References Tool (its name inside of Excel), you’ll need to select Tools » Macro » Visual Basic Editor. On the Tools menu of the VBE, you’ll find Web Services References…. Selecting this brings up the dialog box shown in figure.

The Microsoft Office Web Services Toolkit in action

figs/exhk_0821.gif

You can use the search features in the top left of this dialog to find services through Microsoft’s Universal Discovery, Description and Integration (UDDI) service, or you can enter a URL for the WSDL file at the lower left. You can find a listing of public services at http://xmethods.net/, though you should definitely test to make sure the services still work before you integrate them with your spreadsheets. Many services also require license keys and sometimes license payments, but for this example you’ll use one that is available for free. It returns the IP address for a given domain name.

Start by telling Excel which service you want to use-in this case, http://www.cosme.nu/services/dns.php?wsdl. Enter that value in the URL: box at the bottom left and click Search. A search result of dns will appear in the top right, as shown in figure. Check the box to its left.

Telling the Web Services Toolkit to generate code for a web service

figs/exhk_0822.gif

Clicking the Add button will make Excel generate VBA code for the service, as shown in figure.

VBA code generated by the Web Services Toolkit for accessing the dns service

figs/exhk_0823.gif

Next, close the VBE and set up a very simple spreadsheet such as the one shown in figure.

A spreadsheet for adding web services

figs/exhk_0824.gif

To add a button for calling the service, display the Control toolbar by right-clicking a toolbar and choosing Control Toolbox from the pop-up menu. Click the button icon, and then click the spreadsheet wherever you want the button to go. Right-click the button, and choose Properties from the pop-up menu. Under Name, enter GetData; under Caption, enter Get IP Address. Close the Properties dialog box, and your spreadsheet should look something like that shown in figure.

Spreadsheet with button for calling web services

figs/exhk_0825.gif

To add the final piece, right-click the button you added and choose View Code. In the window that appears, enter this subroutine:

Private Sub GetData_Click( )
    Dim info As New clsws_dns
    Dim name As String
    Dim IP As String
    name = Range("B2").Text
    IP = info.wsm_dns(name)
    Set IPRange = Range("B3")
    IPRange.Value = IP
End Sub

This code is pretty simple. It references the object the toolkit created for the web service, and creates variables for the name and IP address. It collects the name from cell B2, calls the web service with the name as an argument, and then puts the value returned into cell B3. Once you’ve entered this code and closed the VBE, you can leave design mode by making sure the triangle and ruler icon at the left of the Control toolbar isn’t highlighted. The spreadsheet will now enable you to enter a domain name in cell B2. Clicking the Get IP Address button will put the IP address corresponding to that domain name in cell B3. Figures show this spreadsheet in action with different domain names.

A retrieved IP address

figs/exhk_0826.gif

IP address resolution is one of the simpler services out there, but many times services this simple can be very useful in a spreadsheet — for instance, for currency converters, price retrieval, postal code processing, and much more. You don’t even need to learn about SOAP or WSDL to use these services, as the Web Services Toolkit takes care of all of that for you.

A few caveats are worth mentioning, however. First, the computer has to be connected to a network for a web service to work. You probably don’t want to create spreadsheets that depend heavily on web services if their users will be working on them at 30,000 feet and will be thoroughly disconnected. (Spreadsheets such as this one, which uses a web service to populate fields but doesn’t need to be connected constantly, are probably OK.)

The other major issue with web services generally is that the field is in significant flux. At the time of this writing, SOAP had moved from Version 1.1 to 1.2, and a new version of WSDL was under development; what’s more, many people feel UDDI might eventually be replaced with other technologies. For now, be certain to test the services you use, and keep an eye out for new versions of the Office Web Services Toolkit.

by updated Aug 01, 2016

Понравилась статья? Поделить с друзьями:
  • Excel and web query
  • Excel and web page
  • Excel and venn diagram
  • Excel and vba classes
  • Excel and vba book