Compartilhar via


Como: Alterar de dados em uma pasta de trabalho em um servidor em cache

Se aplica a

As informações contidas neste tópico se aplicam apenas às especificado Ferramentas do Visual Studio para o Office projetos e as versões do Microsoft Office.

Tipo de Projeto

  • Projetos de nível de documento

Versão do Microsoft Office

  • O Excel 2007

  • O Excel 2003

For more information, see Recursos disponíveis pelo aplicativo e o tipo de projeto.

Você pode alterar os dados no cache de uma pasta de trabalho do Microsoft Office Excel que faz parte de um projeto de nível de documento Ferramentas do Visual Studio para o Office sem Executando o Excel.Isso torna possível alterar dados em pastas de trabalho de Excel que são armazenados em um servidor.

O código para alterar os dados deve ser fora do assembly principal Ferramentas do Visual Studio para o Office projeto associado ao documento em que você está trabalhando com o, por exemplo em uma página da Web de ASP.NET, um Aplicativo do Console ou um Aplicativo Windows Forms.

Para obter instruções passo a passo para usar o exemplo de código neste tópico, consulte Demonstra Passo a passo: Alterar dados em cache em uma pasta de trabalho em um servidor.

Exemplo

O exemplo de código a seguir primeiro cria uma instância de um dataset tipado chamado AdventureWorksLTDataSet.Avançar, o código usa a classe ServerDocument para acessar uma instância preenchida do mesmo dataset digitado que já é armazenada em cache em uma pasta de trabalho do Excel e, Avançar, lê os dados do dataset em cache para o dataset local.Finalmente, o código modifica o valor de ListPrice em cada linha do dataset local e, em seguida, grava os dados alterados Voltar para o dataset em cache usando a propriedade Xml.

Dim productDataSet As New AdventureWorksDataSet.AdventureWorksLTDataSet()
Dim workbookPath As String = System.Environment.GetFolderPath( _
    Environment.SpecialFolder.MyDocuments) & _
    "\AdventureWorksReport\bin\Debug\AdventureWorksReport.xlsx"
Dim serverDocument1 As ServerDocument = Nothing

Try
    serverDocument1 = New ServerDocument(workbookPath)
    Dim dataHostItem1 As CachedDataHostItem = _
        serverDocument1.CachedData.HostItems("AdventureWorksReport.Sheet1")
    Dim dataItem1 As CachedDataItem = dataHostItem1.CachedData("AdventureWorksLTDataSet")

    If dataItem1 IsNot Nothing Then
        Console.WriteLine("Before reading data from the cache dataset, the local dataset has " & _
            "{0} rows.", productDataSet.Product.Rows.Count.ToString())

        ' Read the cached data from the worksheet dataset into the local dataset.
        Dim schemaReader As New System.IO.StringReader(dataItem1.Schema)
        Dim xmlReader As New System.IO.StringReader(dataItem1.Xml)
        productDataSet.ReadXmlSchema(schemaReader)
        productDataSet.ReadXml(xmlReader)

        Console.WriteLine("After reading data from the cache dataset, the local dataset has " & _
            "{0} rows.", productDataSet.Product.Rows.Count.ToString())

        ' Modify the prices of each product in the local dataset.
        Dim row As AdventureWorksDataSet.AdventureWorksLTDataSet.ProductRow
        For Each row In productDataSet.Product.Rows
            If row.ProductCategoryID < 20 Then
                row.ListPrice = row.ListPrice + row.ListPrice * 0.1
            Else
                row.ListPrice = row.ListPrice - row.ListPrice * 0.1
            End If
        Next row

        ' Write the modified local dataset to the worksheet dataset using the DiffGram format.
        Dim stringIn As New System.Text.StringBuilder()
        Dim stringOut As New System.IO.StringWriter(stringIn)
        productDataSet.WriteXml(stringOut, System.Data.XmlWriteMode.DiffGram)
        dataItem1.Xml = stringIn.ToString()

        serverDocument1.Save()
        Console.WriteLine("The product prices have been modified.")
    Else
        Console.WriteLine("The data object is not found in the data cache.")
    End If
Catch ex As System.IO.FileNotFoundException
    Console.WriteLine("The specified workbook does not exist.")
Catch ex As System.Xml.XmlException
    Console.WriteLine("The data object has invalid XML information.")
Finally
    If Not (serverDocument1 Is Nothing) Then
        serverDocument1.Close()
    End If
    Console.WriteLine(vbLf & vbLf & "Press Enter to close the application.")
    Console.ReadLine()
End Try
AdventureWorksDataSet.AdventureWorksLTDataSet productDataSet =
    new AdventureWorksDataSet.AdventureWorksLTDataSet();
string workbookPath = System.Environment.GetFolderPath(
    Environment.SpecialFolder.MyDocuments) +
    @"\AdventureWorksReport\bin\Debug\AdventureWorksReport.xlsx";
ServerDocument serverDocument1 = null;

try
{
    serverDocument1 = new ServerDocument(workbookPath);
    CachedDataHostItem dataHostItem1 =
        serverDocument1.CachedData.HostItems["AdventureWorksReport.Sheet1"];
    CachedDataItem dataItem1 = dataHostItem1.CachedData["adventureWorksLTDataSet"];

    if (dataItem1 != null)
    {
        Console.WriteLine("Before reading data from the cache dataset, the local dataset has " +
            "{0} rows.", productDataSet.Product.Rows.Count.ToString());

        // Read the cached data from the worksheet dataset into the local dataset.
        System.IO.StringReader schemaReader = new System.IO.StringReader(dataItem1.Schema);
        System.IO.StringReader xmlReader = new System.IO.StringReader(dataItem1.Xml);
        productDataSet.ReadXmlSchema(schemaReader);
        productDataSet.ReadXml(xmlReader);

        Console.WriteLine("After reading data from the cache dataset, the local dataset has " +
            "{0} rows.", productDataSet.Product.Rows.Count.ToString());

        // Modify the prices of each product in the local dataset.
        foreach (AdventureWorksDataSet.AdventureWorksLTDataSet.ProductRow row in 
                 productDataSet.Product.Rows)
        {
            if (row.ProductCategoryID < 20)
            {
                row.ListPrice = row.ListPrice + (row.ListPrice * (Decimal).10);
            }
            else
            {
                row.ListPrice = row.ListPrice - (row.ListPrice * (Decimal).10);
            }
        }

        // Write the modified local dataset to the worksheet dataset using the DiffGram format.
        System.Text.StringBuilder stringIn = new System.Text.StringBuilder();
        System.IO.StringWriter stringOut = new System.IO.StringWriter(stringIn);
        productDataSet.WriteXml(stringOut, System.Data.XmlWriteMode.DiffGram);
        dataItem1.Xml = stringIn.ToString();

        serverDocument1.Save();
        Console.WriteLine("The product prices have been modified.");
    }
    else
    {
        Console.WriteLine("The data object is not found in the data cache.");
    }
}
catch (System.IO.FileNotFoundException)
{
    Console.WriteLine("The specified workbook does not exist.");
}
catch (System.Xml.XmlException)
{
    Console.WriteLine("The data object has invalid XML information.");
}
finally
{
    if (serverDocument1 != null)
    {
        serverDocument1.Close();
    }

    Console.WriteLine("\n\nPress Enter to close the application.");
    Console.ReadLine();
}

Compilando o código

O exemplo de código neste tópico é projetado para ser usado em um Aplicativo do Console que tenha Acessar a um projeto de Biblioteca de Classes que define um dataset tipado e uma pasta de trabalho do Excel que faz parte de uma personalização de nível de documento para o Excel 2003 ou o Excel 2007.Para obter instruções passo a passo para usar o código, consulte Demonstra Passo a passo: Alterar dados em cache em uma pasta de trabalho em um servidor.

Consulte também

Tarefas

Demonstra Passo a passo: Alterar dados em cache em uma pasta de trabalho em um servidor

Como: Armazenar em cache dados para uso off-line ou em um servidor

Como: Recuperar dados de uma pasta de trabalho em um servidor armazenados em cache

Como: Inserir dados em uma pasta de trabalho em um servidor

Conceitos

Acessando dados em documentos no servidor

DiffGrams