Export (0) Print
Expand All

SpreadsheetDocument class

Defines SpreadsheetDocument - an OpenXmlPackage represents a Spreadsheet document.

Namespace:  DocumentFormat.OpenXml.Packaging
Assembly:  DocumentFormat.OpenXml (in DocumentFormat.OpenXml.dll)

public class SpreadsheetDocument : OpenXmlPackage

The following example creates a basic Excel document, a workbook with one worksheet. After you run the code example, take a look at the created file, “SpreadsheetDocumentEx.xlsx,” and notice the worksheet named "mySheet.”

using System;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;

namespace SpreadsheetDocumentEx
{
    class Program
    {
        static void Main(string[] args)
        {
            string fileName = @"c:\Users\Public\Documents\SpreadsheetDocumentEx.xlsx";

            // Create a spreadsheet document by supplying the file name.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.
                Create(fileName, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());

            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.
                AppendChild<Sheets>(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.
                GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);

            // Close the document.
            spreadsheetDocument.Close();

            Console.WriteLine("The spreadsheet document has been created.\nPress a key.");
            Console.ReadKey();
        }
    }
}

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Community Additions

Show:
© 2014 Microsoft