Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

How to use the Office XML file format and the packaging components from the .NET Framework 3.0 to create a simple Excel 2007 workbook or a simple Word 2007 document


View products that this article applies to.

Introduction

This article describes how to use the Microsoft Office XML file format and the packaging components from the Microsoft .NET Framework 3.0 to create a simple Microsoft Office Excel 2007 workbook or a simple Microsoft Office Word 2007 document.

↑ Back to the top


More information

The code examples in this article create a new Excel workbook or a new Word document that contains the text "Hello World" without automating Excel 2007 or Word 2007.

Client requirements

  • Microsoft Visual Studio 2005 or Microsoft Visual C# 2005
  • The .NET Framework 3.0
  • Visual Studio 2005 Extensions for the .NET Framework 3.0
  • Excel 2007 or Word 2007

Step-by-step example

Create the Windows-based application

  1. Start Visual Studio 2005 or Visual C# 2005.
  2. Create a new Visual C# Windows application.
  3. Add a reference to the Windowsbase.dll assembly.

    Note If the Windowsbase.dll reference does not appear on the .NET tab of the Add Reference dialog box, click the Browse tab, locate the C:\Program Files\Reference assemblies\Microsoft\Framework\v3.0 folder, and then click WindowsBase.dll.
  4. In Visual Studio, click Code on the View menu to switch to the Code view.
  5. Add the following directives in the Form1 class.
    	
    	using System.Xml;
    	using System.IO;
    	using System.IO.Packaging;
    
    

Add code to create the Excel workbook

  1. In Visual Studio, click Designer on the View menu to switch to Design view for the form.
  2. Add a Button control to the Windows form. Set the Text property of the button to Create Excel Workbook.
  3. Double-click the Button control to generate the button1_Click event handler.
  4. Add the following code example to the button1_Click event handler. The new event handler code should resemble the following code example.
    	private void button1_Click(object sender, EventArgs e)
            {
                //Create the XML documents.
                XmlDocument workbookDoc = null;
                workbookDoc = CreateExcelXML("workbook");
    
                XmlDocument worksheetDoc = null;
                worksheetDoc = CreateExcelXML("worksheet");
    
                XmlDocument sharedstringsDoc = null;
                sharedstringsDoc = CreateExcelXML("sharedstrings");
    
                //Create the Excel package.
                Package xlPackage = null;
                xlPackage = CreateExcelWorkbookPackage("HelloWorld.xlsx");
    
                //Add the parts to the Excel package.
                if (xlPackage != null)
                {
                    //Add the workbook part.
                    AddExcelPart(xlPackage, "workbook", workbookDoc);
    
                    //Add the worksheet part.
                    AddExcelPart(xlPackage, "worksheet", worksheetDoc);
    
                    //Add the sharedstrings part.
                    AddExcelPart(xlPackage, "sharedstrings", sharedstringsDoc);
    
                }
    
                //Save the changes, and then close the package.
                if (xlPackage != null)
                {
                    xlPackage.Flush();
                    xlPackage.Close();
                }
    
                MessageBox.Show("Successfully created Excel workbook");
            }
    
  5. Add the following code example to the Form1 class. This code example creates and inserts the XML components that contain the Excel worksheets.
    	  private XmlDocument CreateExcelXML(string partType)
            {
                switch (partType)
                {
                    case "workbook":
                        //Create a new XML document for the workbook.
                        XmlDocument workbookDoc = new XmlDocument();
    
                        //Obtain a reference to the root node, and then add
                        //the XML declaration.
                        XmlElement wbRoot = workbookDoc.DocumentElement;
                        XmlDeclaration wbxmldecl = 
    					workbookDoc.CreateXmlDeclaration
    					("1.0", "UTF-8", "yes");
                        workbookDoc.InsertBefore(wbxmldecl, wbRoot);
    
                        //Create and append the workbook node
                        //to the document.
                        XmlElement workBook = 
    					workbookDoc.CreateElement("workbook");
                        workBook.SetAttribute("xmlns",
                            "http://schemas.openxmlformats.org/" +
                            "spreadsheetml/2006/main");
                        workBook.SetAttribute("xmlns:r",
                            "http://schemas.openxmlformats.org/officeDocument/" +
                            "2006/relationships");
                        workbookDoc.AppendChild(workBook);
    
                        //Create and append the sheets node to the 
                        //workBook node.
                        XmlElement sheets = workbookDoc.CreateElement("sheets");
                        workBook.AppendChild(sheets);
    
    
                        //Create and append the sheet node to the 
                        //sheets node.
                        XmlElement sheet = workbookDoc.CreateElement("sheet");
                        sheet.SetAttribute("name", "Sheet1");
                        sheet.SetAttribute("sheetId", "1");
      sheet.SetAttribute("id",
    				"http://schemas.openxmlformats.org/" +
    				"officeDocument/2006/relationships","rId1");
                        sheets.AppendChild(sheet);
    
                        return workbookDoc;
    
                    case "worksheet":
                        //Create a new XML document for the worksheet.
                        XmlDocument worksheetDoc = new XmlDocument();
    
                        //Get a reference to the root node, and then add
                        //the XML declaration.
                        XmlElement wsRoot = worksheetDoc.DocumentElement;
                        XmlDeclaration wsxmldecl = 
                            worksheetDoc.CreateXmlDeclaration("1.0", 
    "UTF-8", "yes");
                        worksheetDoc.InsertBefore(wsxmldecl, wsRoot);
    
    
                        //Create and append the worksheet node
                        //to the document.
                        XmlElement workSheet = 
    					worksheetDoc.CreateElement("worksheet");
                        workSheet.SetAttribute("xmlns",
                            "http://schemas.openxmlformats.org/" +
                            "spreadsheetml/2006/main");
                        workSheet.SetAttribute("xmlns:r",
                            "http://schemas.openxmlformats.org/" +
                            "officeDocument/2006/relationships");
                        worksheetDoc.AppendChild(workSheet);
                                           
                        //Create and add the sheetData node.
                        XmlElement sheetData = 
    					worksheetDoc.CreateElement("sheetData");
                        workSheet.AppendChild(sheetData);
    
                        //Create and add the row node. 
                        XmlElement rNode = worksheetDoc.CreateElement("row");
                        rNode.SetAttribute("r", (1).ToString());
                        rNode.SetAttribute("spans", "1:1");
                        sheetData.AppendChild(rNode);
    
                        //Create and add the column node.
                        XmlElement cNode = worksheetDoc.CreateElement("c");
                        cNode.SetAttribute("r", "A1");
                        cNode.SetAttribute("t", "s");
                        rNode.AppendChild(cNode);
    
                        //Add the "Hello World" text to the worksheet.
                        XmlElement vNode = worksheetDoc.CreateElement("v");
                        vNode.InnerText = "0";
                        cNode.AppendChild(vNode);
    
                        return worksheetDoc;
                        
                    case "sharedstrings":
                        //Create a new XML document for the sharedStrings.
                        XmlDocument sharedStringsDoc = new XmlDocument();
    
                        //Get a reference to the root node, and then add
                        //the XML declaration.
                        XmlElement ssRoot = sharedStringsDoc.DocumentElement;
                        XmlDeclaration ssxmldecl =
                            sharedStringsDoc.CreateXmlDeclaration("1.0", 
    "UTF-8", "yes");
                        sharedStringsDoc.InsertBefore(ssxmldecl, ssRoot);
    
                        //Create and append the sst node.
                        XmlElement sstNode = 
    					sharedStringsDoc.CreateElement("sst");
                        sstNode.SetAttribute("xmlns", 
    					"http://schemas.openxmlformats.org/" +
                            "spreadsheetml/2006/main");
                        sstNode.SetAttribute("count", "1");
                        sstNode.SetAttribute("uniqueCount", "1");
                        sharedStringsDoc.AppendChild(sstNode);
    
                        //Create and append the si node.
                        XmlElement siNode = sharedStringsDoc.CreateElement("si");
                        sstNode.AppendChild(siNode);
    
                        //Create and append the t node.
                        XmlElement tNode = sharedStringsDoc.CreateElement("t");
                        tNode.InnerText = "Hello World";
                        siNode.AppendChild(tNode);
    
                        return sharedStringsDoc;   
             
                    default:
                        return null;
                }
            }
    
            private Package CreateExcelWorkbookPackage(string fileName)
            {
                //Create a new Excel workbook package on the
                //desktop of the user by using the specified name.
                string desktopDir = System.Environment.GetFolderPath(
                            Environment.SpecialFolder.DesktopDirectory);
    
                Package xlPackage = Package.Open(desktopDir + "\\" + fileName,
                        FileMode.Create, FileAccess.ReadWrite);
    
                return xlPackage;
    
            }
    
            private void AddExcelPart(Package fPackage, string part, 
    XmlDocument xDoc)
            {
                switch (part)
                { 
                    case "workbook":
                        string nsWorkbook = "application/vnd.openxmlformats-" +
                                "officedocument.spreadsheetml.sheet.main+xml";
                        string workbookRelationshipType = 
    "http://schemas.openxmlformats.org/" +                            "officeDocument/2006/relationships/" +
    "officeDocument";
                        Uri workBookUri = PackUriHelper.CreatePartUri(new 
                                Uri("xl/workbook.xml",UriKind.Relative));
    
                        //Create the workbook part.
                        PackagePart wbPart =
                                fPackage.CreatePart(workBookUri, nsWorkbook);
    
                        //Write the workbook XML to the workbook part.
                        Stream workbookStream = 
                                wbPart.GetStream(FileMode.Create, 
    					FileAccess.Write);
                        xDoc.Save(workbookStream);
    
                        //Create the relationship for the workbook part.
                        fPackage.CreateRelationship(workBookUri,
                            TargetMode.Internal,
    workbookRelationshipType,"rId1");
    
                        break;
    
                    case "worksheet":
                        string nsWorksheet = "application/vnd.openxmlformats-" +
                                "officedocument.spreadsheetml.worksheet+xml";
                        string worksheetRelationshipType = 
    				"http://schemas.openxmlformats.org/" +
                            "officeDocument/2006/relationships/worksheet";
                        Uri workSheetUri = PackUriHelper.CreatePartUri(new
                              Uri("xl/worksheets/sheet1.xml",UriKind.Relative));
    
                        //Create the workbook part.
                        PackagePart wsPart =
                                fPackage.CreatePart(workSheetUri, nsWorksheet);
    
                        //Write the workbook XML to the workbook part.
                        Stream worksheetStream =
                                  wsPart.GetStream(FileMode.Create, 
    					FileAccess.Write);
                        xDoc.Save(worksheetStream);
    
                        //Create the relationship for the workbook part.
                        Uri wsworkbookPartUri = PackUriHelper.CreatePartUri(new 
                                Uri("xl/workbook.xml",UriKind.Relative));
                        PackagePart wsworkbookPart = 
    					fPackage.GetPart(wsworkbookPartUri);
                        wsworkbookPart.CreateRelationship(workSheetUri,
                                  TargetMode.Internal, 
    worksheetRelationshipType,"rId1");
                        
                        break;
    
                    case "sharedstrings":
                        string nsSharedStrings = 
    				"application/vnd.openxmlformats-officedocument" +
                            ".spreadsheetml.sharedStrings+xml";
                        string sharedStringsRelationshipType = 
    "http://schemas.openxmlformats.org" +                            "/officeDocument/2006/relationships/sharedStrings";
                        Uri sharedStringsUri = PackUriHelper.CreatePartUri(new
                              Uri("xl/sharedStrings.xml", UriKind.Relative));
    
                        //Create the workbook part.
                        PackagePart sharedStringsPart =                          						fPackage.CreatePart(sharedStringsUri,
    nsSharedStrings);
    
                        //Write the workbook XML to the workbook part.
                        Stream sharedStringsStream =
                                sharedStringsPart.GetStream(FileMode.Create,
    FileAccess.Write);
                        xDoc.Save(sharedStringsStream);
    
                        //Create the relationship for the workbook part.
                        Uri ssworkbookPartUri = PackUriHelper.CreatePartUri(new
                                Uri("xl/workbook.xml", UriKind.Relative));
                        PackagePart ssworkbookPart = 
    					fPackage.GetPart(ssworkbookPartUri);
                        ssworkbookPart.CreateRelationship(sharedStringsUri,
                                TargetMode.Internal, 
    					sharedStringsRelationshipType,"rId2");
    
                        break;
                }
            }
    
  6. Save the project.

Add code to create the Word document

  1. In Visual Studio, click Designer on the View menu to switch to Design view for the form.
  2. Add another Button control to the Windows form. Set the Text property of the button to Create Word Document.
  3. Double-click the Button control to generate the button2_Click event handler.
  4. Add code to the button2_Click event handler so that it resembles the following code example.
    	private void button2_Click(object sender, EventArgs e)
            {
                //Create the XML for the Word document.
                XmlDocument xDoc = null;
                xDoc = CreateDocumentXML("Hello World");
    
                //Create the Word document package.
                if (xDoc != null)
                {
                    bool hResult = CreateWordDocumentPackage("HelloWorld.docx",
    			 xDoc);
    
                    if (hResult == true)
                    {
                        MessageBox.Show("Successfully created Word document");
                    }
                }
            }
            
    
  5. Add the following code example to the Form1 class. This code example creates and inserts the XML components that contain the Word document.
    	private XmlDocument CreateDocumentXML(string docText)
            {
                string nsWordML =
                      "http://schemas.openxmlformats.org/wordprocessingml" +
                      "/2006/main";
                
                //Create a new XML document.
                XmlDocument xDoc = new XmlDocument();
    
                //Create and add the document node.
                XmlElement docNode =
                   xDoc.CreateElement("w:document", nsWordML);
                xDoc.AppendChild(docNode);
    
                //Create and add the body node to the 
                //document node.
                XmlElement bodyNode = 
                    xDoc.CreateElement("w:body", nsWordML);
                docNode.AppendChild(bodyNode);
    
                //Create and add the wp node to the docNode.
                XmlElement wpNode =
                   xDoc.CreateElement("w:p", nsWordML);
                bodyNode.AppendChild(wpNode);
    
                //Create and add the wr node to the wpNode.
                XmlElement wrNode =
                   xDoc.CreateElement("w:r", nsWordML);
                wpNode.AppendChild(wrNode);
    
                //Create and add the wt node to the wrNode.
                XmlElement wtNode =
                   (XmlElement)xDoc.CreateNode(XmlNodeType.Element,
                   "w", "t", nsWordML);
                wrNode.AppendChild(wtNode);
    
                //Add the supplied text to the wtNode.
                wtNode.InnerText = docText;
    
                return xDoc;
            }
    
           private bool CreateWordDocumentPackage(string fileName, 
    XmlDocument xDoc)
            {
                try
                {
                    string docContentType = "application/vnd.openxmlformats-" +
                            "officedocument.wordprocessingml." +
                            "document.main+xml";
                    
                    string docRelationshipType = 
    				"http://schemas.openxmlformats.org" +
                            "/officeDocument/2006/relationships/" +
                            "officeDocument";
    
                    //Create a new package file on the desktop of the user by using
                    //the supplied file name.
                    string desktopDir = System.Environment.GetFolderPath(
                            Environment.SpecialFolder.DesktopDirectory);
    
                    Package pkg = Package.Open(desktopDir + "\\" + fileName, 
                          FileMode.Create, FileAccess.ReadWrite);
                    
                                
                    //Create a Uri for the document part.
                    Uri docPartURI = PackUriHelper.CreatePartUri(
                           new Uri("/word/document.xml", 
                           UriKind.Relative));
    
                    //Create the document part.
                    PackagePart pkgPart = 
    				pkg.CreatePart(docPartURI,docContentType);
    
                    //Add the data from XMLDocument to the document part.
                    Stream partStream = pkgPart.GetStream(
                        FileMode.Create, FileAccess.Write);
                       
                    xDoc.Save(partStream);
    
                    //Create a relationship between the document part
                    //and the package.
                    PackageRelationship pkgRelationship = 
                            pkg.CreateRelationship(docPartURI,
                            TargetMode.Internal,docRelationshipType, "rId1");
                    
                    
                    //Flush the changes, and then close the package.
                    pkg.Flush();
                    pkg.Close();
                    
                    return true;
    
                }
                catch (Exception ex)
                {
                    //Display a message to the user the indicates that an error
                    //occurred, and then return a result of false.
                    MessageBox.Show("An error occurred creating the document." +
                        " " + ex.Message,"Error Creating Document",
                        MessageBoxButtons.OK,MessageBoxIcon.Error);
                    return false;
                }
            }
    
  6. In Visual Studio 2005, click Start Debugging on the Debug menu.
  7. Click Create Excel Workbook. A message box appears that indicates that the workbook was successfully created, and a HelloWorld.xlsx file is created on the desktop.
  8. In Excel 2007, open the workbook. Notice that the workbook opens within Excel 2007 and that the Sheet1 worksheet contains the text "Hello World".
  9. Click Create Word Document. A message box appears that indicates that the document was successfully created, and a HelloWorld.docx file is created on the desktop.
  10. In Word 2007, open the document. Notice that the document opens within Word and that the document contains the text "Hello World".

↑ Back to the top


Keywords: KB931866, kbhowto, kbexpertiseinter

↑ Back to the top

Article Info
Article ID : 931866
Revision : 4
Created on : 2/27/2007
Published on : 2/27/2007
Exists online : False
Views : 636