Microsoft KB Archive/931866

= 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 =

Article ID: 931866

Article Last Modified on 2/27/2007

-

APPLIES TO


 * Microsoft Visual Studio 2005 Professional Edition
 * Microsoft Visual Studio 2005 Standard Edition
 * Microsoft Visual Studio 2005 Express Edition
 * Microsoft Office Excel 2007
 * Microsoft Office Word 2007
 * Microsoft .NET Framework 3.0
 * Microsoft Visual C# 2005 Express Edition

-



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.



MORE INFORMATION
The code examples in this article create a new Excel workbook or a new Word document that contains the text &quot;Hello World&quot; 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

Create the Windows-based application
 Start Visual Studio 2005 or Visual C# 2005. Create a new Visual C# Windows application. 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. In Visual Studio, click Code on the View menu to switch to the Code view.  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
 In Visual Studio, click Designer on the View menu to switch to Design view for the form.</li> Add a Button control to the Windows form. Set the Text property of the button to Create Excel Workbook.</li> Double-click the Button control to generate the button1_Click event handler.</li>  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(&quot;workbook&quot;);

XmlDocument worksheetDoc = null; worksheetDoc = CreateExcelXML(&quot;worksheet&quot;);

XmlDocument sharedstringsDoc = null; sharedstringsDoc = CreateExcelXML(&quot;sharedstrings&quot;);

//Create the Excel package. Package xlPackage = null; xlPackage = CreateExcelWorkbookPackage(&quot;HelloWorld.xlsx&quot;);

//Add the parts to the Excel package. if (xlPackage != null) {               //Add the workbook part. AddExcelPart(xlPackage, &quot;workbook&quot;, workbookDoc);

//Add the worksheet part. AddExcelPart(xlPackage, &quot;worksheet&quot;, worksheetDoc);

//Add the sharedstrings part. AddExcelPart(xlPackage, &quot;sharedstrings&quot;, sharedstringsDoc);

}

//Save the changes, and then close the package. if (xlPackage != null) {               xlPackage.Flush; xlPackage.Close; }

MessageBox.Show(&quot;Successfully created Excel workbook&quot;); } </li>  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 &quot;workbook&quot;: //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 (&quot;1.0&quot;, &quot;UTF-8&quot;, &quot;yes&quot;); workbookDoc.InsertBefore(wbxmldecl, wbRoot);

//Create and append the workbook node //to the document. XmlElement workBook = workbookDoc.CreateElement(&quot;workbook&quot;); workBook.SetAttribute(&quot;xmlns&quot;,                       &quot;http://schemas.openxmlformats.org/&quot; +                        &quot;spreadsheetml/2006/main&quot;); workBook.SetAttribute(&quot;xmlns:r&quot;,                       &quot;http://schemas.openxmlformats.org/officeDocument/&quot; +                        &quot;2006/relationships&quot;); workbookDoc.AppendChild(workBook);

//Create and append the sheets node to the //workBook node. XmlElement sheets = workbookDoc.CreateElement(&quot;sheets&quot;); workBook.AppendChild(sheets);

//Create and append the sheet node to the //sheets node. XmlElement sheet = workbookDoc.CreateElement(&quot;sheet&quot;); sheet.SetAttribute(&quot;name&quot;, &quot;Sheet1&quot;); sheet.SetAttribute(&quot;sheetId&quot;, &quot;1&quot;); sheet.SetAttribute(&quot;id&quot;,               &quot;http://schemas.openxmlformats.org/&quot; +                &quot;officeDocument/2006/relationships&quot;,&quot;rId1&quot;); sheets.AppendChild(sheet);

return workbookDoc;

case &quot;worksheet&quot;: //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(&quot;1.0&quot;, &quot;UTF-8&quot;, &quot;yes&quot;); worksheetDoc.InsertBefore(wsxmldecl, wsRoot);

//Create and append the worksheet node //to the document. XmlElement workSheet = worksheetDoc.CreateElement(&quot;worksheet&quot;); workSheet.SetAttribute(&quot;xmlns&quot;,                       &quot;http://schemas.openxmlformats.org/&quot; +                        &quot;spreadsheetml/2006/main&quot;); workSheet.SetAttribute(&quot;xmlns:r&quot;,                       &quot;http://schemas.openxmlformats.org/&quot; +                        &quot;officeDocument/2006/relationships&quot;); worksheetDoc.AppendChild(workSheet); //Create and add the sheetData node. XmlElement sheetData = worksheetDoc.CreateElement(&quot;sheetData&quot;); workSheet.AppendChild(sheetData);

//Create and add the row node. XmlElement rNode = worksheetDoc.CreateElement(&quot;row&quot;); rNode.SetAttribute(&quot;r&quot;, (1).ToString); rNode.SetAttribute(&quot;spans&quot;, &quot;1:1&quot;); sheetData.AppendChild(rNode);

//Create and add the column node. XmlElement cNode = worksheetDoc.CreateElement(&quot;c&quot;); cNode.SetAttribute(&quot;r&quot;, &quot;A1&quot;); cNode.SetAttribute(&quot;t&quot;, &quot;s&quot;); rNode.AppendChild(cNode);

//Add the &quot;Hello World&quot; text to the worksheet. XmlElement vNode = worksheetDoc.CreateElement(&quot;v&quot;); vNode.InnerText = &quot;0&quot;; cNode.AppendChild(vNode);

return worksheetDoc; case &quot;sharedstrings&quot;: //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(&quot;1.0&quot;, &quot;UTF-8&quot;, &quot;yes&quot;); sharedStringsDoc.InsertBefore(ssxmldecl, ssRoot);

//Create and append the sst node. XmlElement sstNode = sharedStringsDoc.CreateElement(&quot;sst&quot;); sstNode.SetAttribute(&quot;xmlns&quot;,                    &quot;http://schemas.openxmlformats.org/&quot; +                        &quot;spreadsheetml/2006/main&quot;); sstNode.SetAttribute(&quot;count&quot;, &quot;1&quot;); sstNode.SetAttribute(&quot;uniqueCount&quot;, &quot;1&quot;); sharedStringsDoc.AppendChild(sstNode);

//Create and append the si node. XmlElement siNode = sharedStringsDoc.CreateElement(&quot;si&quot;); sstNode.AppendChild(siNode);

//Create and append the t node. XmlElement tNode = sharedStringsDoc.CreateElement(&quot;t&quot;); tNode.InnerText = &quot;Hello World&quot;; 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 + &quot;\\&quot; + fileName,                   FileMode.Create, FileAccess.ReadWrite);

return xlPackage;

}

private void AddExcelPart(Package fPackage, string part, XmlDocument xDoc) {           switch (part) {                case &quot;workbook&quot;: string nsWorkbook = &quot;application/vnd.openxmlformats-&quot; + &quot;officedocument.spreadsheetml.sheet.main+xml&quot;; string workbookRelationshipType = &quot;http://schemas.openxmlformats.org/&quot; +                           &quot;officeDocument/2006/relationships/&quot; + &quot;officeDocument&quot;; Uri workBookUri = PackUriHelper.CreatePartUri(new                            Uri(&quot;xl/workbook.xml&quot;,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,&quot;rId1&quot;);

break;

case &quot;worksheet&quot;: string nsWorksheet = &quot;application/vnd.openxmlformats-&quot; + &quot;officedocument.spreadsheetml.worksheet+xml&quot;; string worksheetRelationshipType = &quot;http://schemas.openxmlformats.org/&quot; + &quot;officeDocument/2006/relationships/worksheet&quot;; Uri workSheetUri = PackUriHelper.CreatePartUri(new                         Uri(&quot;xl/worksheets/sheet1.xml&quot;,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(&quot;xl/workbook.xml&quot;,UriKind.Relative)); PackagePart wsworkbookPart = fPackage.GetPart(wsworkbookPartUri); wsworkbookPart.CreateRelationship(workSheetUri,                             TargetMode.Internal, worksheetRelationshipType,&quot;rId1&quot;); break;

case &quot;sharedstrings&quot;: string nsSharedStrings = &quot;application/vnd.openxmlformats-officedocument&quot; + &quot;.spreadsheetml.sharedStrings+xml&quot;; string sharedStringsRelationshipType = &quot;http://schemas.openxmlformats.org&quot; +                           &quot;/officeDocument/2006/relationships/sharedStrings&quot;; Uri sharedStringsUri = PackUriHelper.CreatePartUri(new                         Uri(&quot;xl/sharedStrings.xml&quot;, 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(&quot;xl/workbook.xml&quot;, UriKind.Relative)); PackagePart ssworkbookPart = fPackage.GetPart(ssworkbookPartUri); ssworkbookPart.CreateRelationship(sharedStringsUri,                           TargetMode.Internal,                     sharedStringsRelationshipType,&quot;rId2&quot;);

break; }       } </li> Save the project.</li></ol>

Add code to create the Word document
 In Visual Studio, click Designer on the View menu to switch to Design view for the form.</li> Add another Button control to the Windows form. Set the Text property of the button to Create Word Document.</li> Double-click the Button control to generate the button2_Click event handler.</li>  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(&quot;Hello World&quot;);

//Create the Word document package. if (xDoc != null) {               bool hResult = CreateWordDocumentPackage(&quot;HelloWorld.docx&quot;,             xDoc);

if (hResult == true) {                   MessageBox.Show(&quot;Successfully created Word document&quot;); }           }        }        </li>  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 = &quot;http://schemas.openxmlformats.org/wordprocessingml&quot; + &quot;/2006/main&quot;; //Create a new XML document. XmlDocument xDoc = new XmlDocument;

//Create and add the document node. XmlElement docNode = xDoc.CreateElement(&quot;w:document&quot;, nsWordML); xDoc.AppendChild(docNode);

//Create and add the body node to the //document node. XmlElement bodyNode = xDoc.CreateElement(&quot;w:body&quot;, nsWordML); docNode.AppendChild(bodyNode);

//Create and add the wp node to the docNode. XmlElement wpNode = xDoc.CreateElement(&quot;w:p&quot;, nsWordML); bodyNode.AppendChild(wpNode);

//Create and add the wr node to the wpNode. XmlElement wrNode = xDoc.CreateElement(&quot;w:r&quot;, nsWordML); wpNode.AppendChild(wrNode);

//Create and add the wt node to the wrNode. XmlElement wtNode = (XmlElement)xDoc.CreateNode(XmlNodeType.Element,              &quot;w&quot;, &quot;t&quot;, 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 = &quot;application/vnd.openxmlformats-&quot; + &quot;officedocument.wordprocessingml.&quot; + &quot;document.main+xml&quot;; string docRelationshipType = &quot;http://schemas.openxmlformats.org&quot; + &quot;/officeDocument/2006/relationships/&quot; + &quot;officeDocument&quot;;

//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 + &quot;\\&quot; + fileName,                      FileMode.Create, FileAccess.ReadWrite); //Create a Uri for the document part. Uri docPartURI = PackUriHelper.CreatePartUri(                      new Uri(&quot;/word/document.xml&quot;, 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, &quot;rId1&quot;); //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(&quot;An error occurred creating the document.&quot; +                   &quot; &quot; + ex.Message,&quot;Error Creating Document&quot;,                    MessageBoxButtons.OK,MessageBoxIcon.Error); return false; }       } </li> In Visual Studio 2005, click Start Debugging on the Debug menu.</li> 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.</li> In Excel 2007, open the workbook. Notice that the workbook opens within Excel 2007 and that the Sheet1 worksheet contains the text &quot;Hello World&quot;.</li> 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.</li> In Word 2007, open the document. Notice that the document opens within Word and that the document contains the text &quot;Hello World&quot;.</li></ol>

Keywords: kbexpertiseinter kbhowto KB931866

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.