How to: Insert Data into a Workbook on a Server

Applies to

The information in this topic applies only to the specified Visual Studio Tools for Office projects and versions of Microsoft Office.

Project type

  • Document-level projects

Microsoft Office version

  • Excel 2007

  • Excel 2003

For more information, see Features Available by Application and Project Type.

You can insert data into the cache of a Microsoft Office Excel workbook that is part of a document-level Visual Studio Tools for Office project without running Excel. This makes it possible to insert data into Excel workbooks that are stored on a server.

The code to insert the data must be outside of the main Visual Studio Tools for Office project assembly that is associated with the document you are working with, for example in a Console or Windows Forms application.

For step-by-step instructions for using the code example in this topic, see Walkthrough: Inserting Data into a Workbook on a Server.

The following code example first creates an instance of a typed dataset named AdventureWorksLTDataSet and then fills the Product table in the dataset by using a table adapter. Next, the code uses the ServerDocument class to access an instance of the same typed dataset that is cached in an Excel workbook, and then writes the data from the local dataset into the cached dataset by using the SerializeDataInstance method.

AdventureWorksDataSet.AdventureWorksLTDataSet productDataSet = 
    new AdventureWorksDataSet.AdventureWorksLTDataSet();
AdventureWorksDataSet.AdventureWorksLTDataSetTableAdapters.ProductTableAdapter productTableAdapter =
    new AdventureWorksDataSet.AdventureWorksLTDataSetTableAdapters.ProductTableAdapter();

string workbookPath = System.Environment.GetFolderPath(
    Environment.SpecialFolder.MyDocuments) +
ServerDocument serverDocument1 = null;

    Console.WriteLine("The local dataset is filled.");

    serverDocument1 = new ServerDocument(workbookPath);
    CachedDataHostItem dataHostItem1 =
    CachedDataItem dataItem1 = dataHostItem1.CachedData["adventureWorksLTDataSet"];

    // Initialize the worksheet dataset with the local dataset. 
    if (dataItem1 != null)
        Console.WriteLine("The data is saved to the data cache.");
        Console.WriteLine("The data object is not found in the data cache.");
catch (System.Data.SqlClient.SqlException ex)
catch (System.IO.FileNotFoundException)
    Console.WriteLine("The specified workbook does not exist.");
    if (serverDocument1 != null)

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

The code example in this topic is designed to be used in a Console application that has access to a Class Library project that defines a typed dataset, and an Excel workbook that is part of a document-level customization for Excel 2003 or Excel 2007. For step-by-step instructions for using the code, see Walkthrough: Inserting Data into a Workbook on a Server.

Community Additions