방법: 서버에 있는 통합 문서에서 캐시된 데이터 변경

Excel을 실행하지 않고도 문서 수준 프로젝트의 일부인 Microsoft Office Excel 통합 문서의 캐시에 있는 데이터를 변경할 수 있습니다. 이렇게 하면 서버에 저장되어 있는 Excel 통합 문서에서 데이터를 변경할 수 있습니다.

적용 대상: 이 항목의 정보는 Excel 2007 및 Excel 2010의 문서 수준 프로젝트에 적용됩니다. 자세한 내용은 Office 응용 프로그램 및 프로젝트 형식에 따라 사용 가능한 기능을 참조하십시오.

데이터를 변경하는 코드는 작업 중인 문서와 연결되어 있는 주 프로젝트 어셈블리의 외부, 즉 ASP.NET 웹 페이지, 콘솔 응용 프로그램 또는 Windows Forms 응용 프로그램 등에 있어야 합니다.

이 항목의 코드 예제 사용에 대한 단계별 지침은 연습: 서버의 통합 문서에서 캐시된 데이터 변경을 참조하십시오.

예제

다음 코드 예제에서는 먼저 AdventureWorksLTDataSet이라는 형식화된 데이터 집합의 인스턴스를 만듭니다. 그런 다음 ServerDocument 클래스를 사용하여 Excel 통합 문서에 이미 캐시되어 있는 형식화된 동일한 데이터 집합의 채워진 인스턴스에 액세스하고 이 캐시된 데이터 집합의 데이터를 로컬 데이터 집합으로 읽어 들입니다. 마지막으로 로컬 데이터 집합의 각 행에 있는 ListPrice 값을 수정하고 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();
}

코드 컴파일

이 항목의 코드 예제는 다음 응용 프로그램과 함께 사용할 수 있습니다.

  • 형식화된 데이터 집합을 정의하는 클래스 라이브러리 프로젝트에 액세스할 수 있는 콘솔 응용 프로그램. 코드는 콘솔 응용 프로그램에서 실행됩니다.

  • Excel에 대한 문서 수준 사용자 지정의 일부인 Excel 통합 문서. 이 통합 문서에는 일부 데이터를 포함하는 AdventureWorksLTDataSet이라는 캐시된 데이터 집합이 있습니다.

코드 사용에 대한 단계별 지침은 연습: 서버의 통합 문서에서 캐시된 데이터 변경을 참조하십시오.

참고 항목

작업

연습: 서버의 통합 문서에서 캐시된 데이터 변경

방법: 오프라인이나 서버에서 사용할 데이터 캐싱

방법: 서버에 있는 통합 문서에서 캐시된 데이터 검색

방법: 서버에 있는 통합 문서에 데이터 삽입

개념

서버에 있는 문서의 데이터 액세스

DiffGrams(ADO.NET)