Condividi tramite


Procedura: modificare i dati memorizzati nella cache di una cartella di lavoro di un server

Aggiornamento: novembre 2007

Si applica a

Le informazioni contenute in questo argomento riguardano solo i progetti Visual Studio Tools per Office e le versioni di Microsoft Office specificati.

Tipo di progetto

  • Progetti a livello di documento

Versione Microsoft Office

  • Excel 2007

  • Excel 2003

Per ulteriori informazioni, vedere la classe Funzionalità disponibili in base ai tipi di progetto e applicazione.

È possibile modificare i dati memorizzati nella cache di una cartella di lavoro di Microsoft Office Excel che fa parte di un progetto Visual Studio Tools per Office a livello di documento senza eseguire Excel, consentendo in tal modo la modifica dei dati nelle cartelle di lavoro di Excel memorizzate su un server.

Il codice per la modifica dei dati deve trovarsi all'esterno dell'assembly del progetto Visual Studio Tools per Office principale associato al documento che si sta utilizzando, ad esempio in una pagina Web ASP.NET, un'applicazione console o un'applicazione Windows Form.

Per ottenere istruzioni dettagliate sull'utilizzo dell'esempio di codice contenuto in questo argomento, vedere Procedura dettagliata: modifica dei dati memorizzati nella cache di una cartella di lavoro di un server.

Esempio

Nell'esempio di codice seguente viene anzitutto creata un'istanza di un dataset tipizzato denominato AdventureWorksLTDataSet. Quindi, dopo aver utilizzato la classe ServerDocument per accedere a un'istanza popolata dello stesso dataset tipizzato già memorizzato nella cache di una cartella di lavoro di Excel, il codice legge i dati contenuti nel dataset memorizzato nella cache e li inserisce nel dataset locale. Infine, il codice modifica il valore ListPrice in ogni riga del dataset locale e quindi riscrive i dati modificati nel dataset memorizzato nella cache tramite la proprietà 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();
}

Compilazione del codice

L'esempio di codice contenuto in questo argomento è progettato per essere utilizzato in un'applicazione console in grado di accedere a un progetto Libreria di classi che definisce un dataset tipizzato nonché a una cartella di lavoro di Excel appartenente a una personalizzazione a livello di documento per Excel 2003 o Excel 2007. Per istruzioni dettagliate sull'utilizzo del codice, vedere Procedura dettagliata: modifica dei dati memorizzati nella cache di una cartella di lavoro di un server.

Vedere anche

Attività

Procedura dettagliata: modifica dei dati memorizzati nella cache di una cartella di lavoro di un server

Procedura: memorizzare dati nella cache per l'utilizzo non in linea o su un server

Procedura: recuperare i dati memorizzati nella cache di una cartella di lavoro di un server

Procedura: inserire dati in una cartella di lavoro sul server

Concetti

Accesso ai dati dei documenti sul server

DiffGram (ADO.NET)