Поделиться через


Получение всей книги или моментального снимка

This example shows how to get an entire workbook, a snapshot of the entire file, or just a snapshot of the viewable sheets or objects in the file by using Веб-службы Excel. Getting the workbook or a snapshot is useful if you want to save a copy of the up-to-date workbook, store it somewhere, send it to someone, and so on.

A snapshot is a workbook generated by Службы вычислений Excel, and it represents the current state of the workbook in the Службы Excel session. Some snapshots (known as "published item snapshots") contain only those portions of the Excel file that an author selects as viewable when saving the file to the server. Snapshots contain the layout and formats of the original file, and up-to-date values calculated by Службы вычислений Excel, but they do not contain Excel formulas or external data connections. Службы Excel opens the Excel file on the server, refreshes data sources, and calculates all Excel formulas. When a user or application requests a snapshot, Службы Excel then generates and sends a snapshot back through the Web service API. You can acquire a snapshot of a workbook you already saved to the server, even if you do not have the rights to access the actual file on the server.

You use the Web service's GetWorkbook method to get either the entire workbook or one of the snapshot types. For example, the following code returns a snapshot of the entire Excel workbook. It uses the WorkbookType.FullSnapshot enumeration as the second argument in the GetWorkbook method.


byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.FullSnapshot, out status);
Dim workbook() As Byte = xlService.GetWorkbook(sessionId, WorkbookType.FullSnapshot, status)

Метод GetWorkbook возвращает массив байтов в том же формате файла Excel, что и загруженный в сеанс. Чтобы получить снимок элементов, которые автор книги Excel выбрал как доступные для просмотра при сохранении книги Excel на сервере, используйте перечисление WorkbookType.PublishedItemsSnapshot, как показано ниже:

byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.PublishedItemsSnapshot, out status);
Dim workbook() As Byte = xlService.GetWorkbook(sessionId, WorkbookType.FullSnapshot, status)

Чтобы получить снимок всей книги в текущем состоянии сеанса, используйте перечисление WorkbookType.FullWorkbook:

byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.FullWorkbook, out status);
Dim workbook() As Byte = xlService.GetWorkbook(sessionId, WorkbookType.FullWorkbook, status)

The WorkbookType.FullWorkbook option works only if the user has open rights to the file; if the user has view-only rights, the call will fail.In some cases, your code would need to save the result of a GetWorkbook call. For a discussion about how to save a workbook, see the How to: Save a Workbook example.For more information about the GetWorkbook method and the WorkbookType enumeration, see the Веб-службы Excel reference documentation.

Пример

The following program (a console application) receives one command-line argument, which is the path to the workbook on the server. The program calls the Web service to open the workbook on the server and get a snapshot. It then writes it to standard output so that you can redirect it to a new snapshot file.

using System;
using System.IO;
using System.Text;
using System.Web.Services.Protocols;
// TODO: Change the using GetSnapshot.myServer02 statement
// to point to the Web service you are referencing.
using GetSnapshot.myServer02;

namespace GetSnapshot
{
    class ExcelServicesSnapshot
    {
        static void Main(string[] args)
        {
            try
            {
                if (args.Length < 1)
                {
                    Console.Error.WriteLine("Command line arguments should be: GetSnapshot [workbook_path] > [snapshot_filename]");
                    return;
                }
                // Instantiate the Web service and
                // create a status array object.
                ExcelService xlService = new ExcelService();
                Status[] status;

                xlService.Timeout = 600000;
                // Set credentials for requests.
                // Use the current user's logon credentials.
                xlService.Credentials =
                    System.Net.CredentialCache.DefaultCredentials;

                // Open the workbook, then call GetWorkbook
                // and close the session.
                string sessionId = xlService.OpenWorkbook(args[0], "en-US", "en-US", out status);
                byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.PublishedItemsSnapshot, out status);
                // byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.FullWorkbook, out status);
                // byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.FullSnapshot, out status);

                // Close the workbook. This also closes the session.
                status = xlService.CloseWorkbook(sessionId);

                // Write the resulting Excel file to stdout
                // as a binary stream.
                BinaryWriter binaryWriter = new BinaryWriter(Console.OpenStandardOutput());
                binaryWriter.Write(workbook);
                binaryWriter.Close();
            }

            catch (SoapException e)
            {
                Console.WriteLine("SOAP Exception Message: {0}", e.Message);
            }

            catch (Exception e)
            {
                Console.WriteLine("Exception Message: {0}", e.Message);
            }
        }
    }
}

Imports System
Imports System.IO
Imports System.Text
Imports System.Web.Services.Protocols
' TODO: Change the using GetSnapshot.myServer02 statement
' to point to the Web service you are referencing.
Imports GetSnapshot.myServer02

Namespace GetSnapshot
    Friend Class ExcelServicesSnapshot
        Shared Sub Main(ByVal args() As String)
            Try
                If args.Length < 1 Then
                    Console.Error.WriteLine("Command line arguments should be: GetSnapshot [workbook_path] > [snapshot_filename]")
                    Return
                End If
                ' Instantiate the Web service and
                ' create a status array object.
                Dim xlService As New ExcelService()
                Dim status() As Status

                xlService.Timeout = 600000
                ' Set credentials for requests.
                ' Use the current user's logon credentials.
                xlService.Credentials = System.Net.CredentialCache.DefaultCredentials

                ' Open the workbook, then call GetWorkbook
                ' and close the session.
                Dim sessionId As String = xlService.OpenWorkbook(args(0), "en-US", "en-US", status)
                Dim workbook() As Byte = xlService.GetWorkbook(sessionId, WorkbookType.PublishedItemsSnapshot, status)
                ' byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.FullWorkbook, out status);
                ' byte[] workbook = xlService.GetWorkbook(sessionId, WorkbookType.FullSnapshot, out status);

                ' Close the workbook. This also closes the session.
                status = xlService.CloseWorkbook(sessionId)

                ' Write the resulting Excel file to stdout
                ' as a binary stream.
                Dim binaryWriter As New BinaryWriter(Console.OpenStandardOutput())
                binaryWriter.Write(workbook)
                binaryWriter.Close()

            Catch e As SoapException
                Console.WriteLine("SOAP Exception Message: {0}", e.Message)

            Catch e As Exception
                Console.WriteLine("Exception Message: {0}", e.Message)
            End Try
        End Sub
    End Class
End Namespace

Используйте следующие аргументы в командной строке для запуска приложения GetSnapshot:


GetSnapshot.exe [workbook_path] > [snapshot_filename]

Пример:

C:\\>GetSnapshot.exe http://myServer02/reports/reports/OriginalWorkbook.xlsx > SnapshotCopy.xlsx

В предыдущем примере программа GetSnapshot помещает новый файл в каталог "C:\".

Примечание.

Книга, снимок которой нужно создать, должна находиться в надежном расположении.

Надежное программирование

Make sure you add a Web reference to an Веб-службы Excel site you have access to. Измените оператор, using GetSnapshot.myServer02; чтобы он указывал на сайт веб-службы, на который вы ссылаетесь.

См. также

Задачи

Как сделать расположение доверенным

Понятия

Доступ к API SOAP

Другие ресурсы

Шаг 1. Создание проекта клиента веб-службы

Этап 2. Добавление веб-ссылки

Этап 3. Получение доступа к веб-службе

Этап 4. Построение и тестирование приложения

Пошаговое руководство. Разработка настраиваемого приложения с помощью веб-служб Excel