using …

Pure C#

11 Ara_Aralık_kısaltma 2008 için Arşiv

Creating an Open XML Document in .NET

Yazan: esersahin 11/12/2008

http://openxmldeveloper.org/articles/OpenXMLDocFromDotNet.aspx

Article author: Sanjay Kumar Madhva, Sonata Software Limited

Introduction

The idea of this article is to show how easy it is to create an OpenXML WordprocessingML using .NET and using System.IO.Packaging provided by WinFx.

What we need, is to create a windows application that lets user enter multi line of text. The user is provided a button that on click creates a WordprocessingML. When the user clicks on the button all we need to code for, breaking the user entered text into paragraphs and creating an document.xml as shown below. Package it into an OpenXML document.

Content of document.xml

Here are twelve easy steps to create a word processing document like the one above and write it out as a valid Open XML document …

Step 1. Create a new C# project.

Create a new project “WordDocCreator” in a new solution.

Step 2. Add reference to WindowsBase provided WinFx.

Right click on the reference and form the pop up menu select “Add Reference”

Add reference windows pops up. Select “Windows Base” from the .NET tab as shown in the fig below.

Step 3. Add a Text box to the form

Drag and drop TextBox from the ToolBox on to the form.

Step 4. Change the textbox to accept MultiLine.

Change the textbox property to accept multiline.

Step 5. Resize the textbox

Resize the textbox to fit to the screen.

Step 6. Add two Buttons.

Step 7. Rename the text box, and the two buttons.

  • Change the forms title text to Document Creator
  • Rename the Text box to mleTextForDocument
  • Command button 1 to Exit and change the text to “E&xit”
  • Command button 2 to GenerateDocument and change the text to “&Generate Document”

Step 8. Code for close event of Exit button

Double click on the exit button to generate the click event for the button add close() in the button clicked event as shown below.

private void Exit_Click(object sender, EventArgs e)
{
close();
}

Step 9. Add using directive

using System.Xml;
using System.IO;
using System.IO.Packaging;

Step 10. Create a method to get the save file name and path.

We may have to create a file dialog that will accept a filename from the user. We can call the SaveFileDialog provided by the .net framework to get the directory and the name of the file in which the user wants to save the document content.

The code is as follows.

//Get the file path where the user wants to save the document.
private string GetSavePath()
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.AddExtension = true;
//Get only Docx file
sfd.Filter = “docx|”;
sfd.CheckPathExists = true;
sfd.DefaultExt = “.docx”;
sfd.ShowDialog();
return sfd.FileName; // return the filename and the path
}

Step 11. Code for close event of GenerateDocument button

The document creation can be achieved by following 5 easy steps:
1. Take the text entered by the user in the multilane edit has to be split into paragraph and creating an “document.xml” as shown under “Content of document.xml”.
2. Creating an instance of Package class
3. Create the main document part (document.xml) using the package class.
4. Create the relationship file.
5. Close the document.

private void GenerateDocument_Click(object sender, EventArgs e)
{
string _nameSpaceURI = “http://schemas.microsoft.com/office/word/2005/10/wordml”;
string docFileName = GetSavePath();

//– Step 1 – Creating the document xml
XmlDocument doc = new XmlDocument();
XmlElement _wWordDoc = doc.CreateElement(“w:wordDocument”, _nameSpaceURI);
doc.AppendChild (_wWordDoc);
XmlElement _wbody = doc.CreateElement(“w:body”,_nameSpaceURI);
_wWordDoc.AppendChild(_wbody);
// Check if the string contains a line feed
string[] _SplitStr = mleTextForDocument.Text.Split(‘\n’);
// if it contains line feed then each entry with a line feed goes to a new paragraph.
for (int row = 0; row < _SplitStr.Length; row++)
{
XmlElement _wp1 = doc.CreateElement(“w:p”,_nameSpaceURI);
_wbody.AppendChild(_wp1);
XmlElement _wr1 = doc.CreateElement(“w:r”, _nameSpaceURI);
_wp1.AppendChild(_wr1);
XmlElement _wt11 = doc.CreateElement(“w:t”, _nameSpaceURI);
_wr1.AppendChild(_wt11);
XmlNode _wt1 = doc.CreateNode(XmlNodeType.Text, “w:t”,_nameSpaceURI);
_wt1.Value = _SplitStr[row];
_wt11.AppendChild(_wt1);
}

//– Step 2 – Creating the Package
Package package = null;
package = Package.Open(docFileName, FileMode.Create, FileAccess.ReadWrite);

//– Step 3 – Create the main document part (document.xml)
Uri uri = new Uri(“/word/document.xml”, UriKind.Relative);
PackagePart part = package.CreatePart(uri, “application/vnd.ms-word.main+xml”);
StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Create, FileAccess.Write));
doc.Save(partWrt);
partWrt.Close();
package.Flush();

//– Step 4 – Create the relationship file
uri = new Uri(“/word/document.xml”, UriKind.Relative);
PackageRelationship rel = package.CreateRelationship(uri, TargetMode.Internal, “http://schemas.microsoft.com/office/2006/relationships/officeDocument”, “rId1″);
package.Flush();

//– Step 5- Close the document.
package.Close();
}

Step 12. Build and Run.

From the Build menu select “Build WordDocument”

To run with out debug, select “Start Without Debugging” under “Debug” menu or press Ctrl+F5.

Application window appears.

Key in some text and click on “Generate Document” button, a file dialog appears. Provide the file name and click save.

Note: remember the save in directory.

Open file explorer and go the above-specified directory. Double click on the document you just created.

See the content you typed being displayed as a document …

Published Wednesday, April 12, 2006 4:39 PM by dmahugh
Filed Under: , ,
Attachment(s): WordDocCreator.zip

Comments

 

jkemmery said:

Excellent primer. Thank you.
April 14, 2006 10:33 AM
 

planks said:

I tried the example, it creates the .docx file and everything but when I tried to open it it displays an error that there are missing elements. When I see the files I notice that nothing is written in them, in the document.xml nor in the relationships file.

I also sent the output to be displayed in the console and it is doing it as it should so I think there’s something about file writing permissions, any ideas?

May 19, 2006 1:13 PM
 

SanjayKumarM said:

If you are using Office 2007 Beta2 then you may have to make the following changes to make tha application work
1.
Seach for->
http://schemas.microsoft.com/office/word/2005/10/wordml
replace with->
http://schemas.openxmlformats.org/wordprocessingml/2006/3/main

2.
Seach for-> application/vnd.ms-word.main+xml
replace with->
application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml

3.
Seach for->
http://schemas.microsoft.com/office/2006/relationships/officeDocument
replace with->
http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument

May 24, 2006 4:46 AM
 

SanjayKumarM said:

Hi Planks.
     The code was written for Office 2007 Beta1, I have also posted the changes to be made to make it workable for Beta 2.

     I have really tested the code it works, May be the version of WinFx or office 12 you are using may mot be the corrent one.

    If you want I can email the code to you.

Sanjay

May 24, 2006 4:49 AM
 

radwagner said:

Sanjay,

I’m pleased to see your example as this is exactly what I’m looking for. However, when I open the document created by the sample in Office 12 Beta 2, I get “Elements and Attributes in restricted namespaces are not allowed”. Location: Part: /word/document.xml Line: 2, Column: 89. Other samples I’ve tried as posted give the same details.

Thanks,
RW

May 30, 2006 10:33 AM
 

ivofoi said:

I’m having problems with the code above. It does what I need, but when the .docx file is created and I try to open it, Word 2007 returns an error:
“The Office Open XML file try.docx cannot be opened because there are problems with the contents.” and
“Microsoft Office cannot open this file because some parts are missing or invalid.”.
Can anyone help me with this problem?
thx
April 3, 2007 11:11 AM
 

ivofoi said:

Forgot to mention – I’m not using any beta version of MS Office, but the final version.
April 3, 2007 11:19 AM

Yazı kategorisi: Open XML | » yorum bırak;

Learning Resources for Open XML SDK

Yazan: esersahin 11/12/2008

https://connect.microsoft.com/content/content.aspx?SiteID=589&ContentID=9924

1          The Open XML Standard

Standard ECMA-376, and Ecma TC45

ISO/IEC DIS 29500

2          SDK Team Resource

MSDN library for SDK version 1.0 and 2.0

Download page for SDK version 1.0 and 2.0

Microsoft Connect: Open XML SDK

3          Microsoft-wide Resource

XML in Office Developer Portal: This portal contains technical articles, code samples, developer documentation, and multimedia presentations on working with XML in Office.

Open XML Formats Resource Center: This contains developer resources to help you get started generating and manipulating documents, workbooks, and presentations using the Open XML Formats.

Microsoft Visual Studio Tools for the Office System Power Tools: A set of developer tools that provide additional functionality useful in Office-based development.

4          Forum

MSDN forum

5          Blog

Erik White, Doug Mahugh, Brian Jones, Gray Knowlton, Oliver BellJason Matusow

6          Tech Site

Openxmldeveloper

Openxmlcommunity

7          3rd Party Software

Powertools: PowerTools for Open XML are sample source code and guidance for developers showing how to build PowerShell cmdlets to create and modify Office Open XML documents, and scripts to demonstrate the use of the cmdlets.

ExcelPackage: ExcelPackage provides server-side generation of Excel 2007 spreadsheets.

Open XML Package Explorer: This tool allows full editing of Open XML packages, creating new packages and various other features.

OpenXmlDiff by Pranav Wagh: a simple and straightforward tool that generates a report of all the differences between two Open XML documents.

XMLSpy: XMLSpy provides powerful support for accessing, editing, transforming, and querying XML data saved in Microsoft® Office 2007 documents and other zipped files.

DiffDog: This tool supports to diff/merge Office Open XML files and ZIP archives.

Stylevision: Stylevision allows to graphically design and implement conformant DOCX output from XML and/or database data.

Mapforce: It auto-generates C# code that creates an Open XML spreadsheet.

openxml4j: OpenXML4J is a Java library dedicated to the creation and manipulation of Office Open XML (ECMA-376) and OPC based documents (for example Office 2007 Word, Excel and PowerPoint documents).

PHPExcel: This project provides a set of classes for the PHP programming language, which allow you to write to Excel 2007 files and read from Excel 2007 files. This project is built around Microsoft’s OpenXML standard and PHP.

<oxygen/> XML Editor: This editor allows you to extract, validate, edit and process the XML data stored in Office 2007 files and any other ZIP-based archive. Validation is done using the latest ECMA XML Schemas.

docx4all: currently you can create, open, edit, and print simple docx on Windows, Linux and OSX (with latest Java). You can collaborate with people using the plutext Word 2007 add-in. Table support is on its way.

8          Related Techs

.Net Framework 3.5, which includes LINQ and XML technology.

9          Other resources

Open XML SDK Demo On PDC2008: Open XML SDK V2 demo by Zeyad Rajabi on PDC2008 (size:178M).

Open XML SDK V1 Technical Chat video: Open XML SDK V1 demo and road map by Eric White and Zeyad Rajabi.

OpenXML in wikipedia

Yazı kategorisi: Open XML | » yorum bırak;

Open XML SDK Articles

Yazan: esersahin 11/12/2008

https://connect.microsoft.com/content/contentlist.aspx?ContentTypeID=1&SiteID=589&wa=wsignin1.0

  • Creating Table in WordprocessingML
    V2 CTP1 Article
  • Retrieving Custom Xml Data in WordprocessingML
    V2 CTP1 Article
  • Reading Content Control Data in WordprocessingML
    V2 CTP1 Article
  • Sample code: CreateTableWithDataSet
    V2 CTP1 sample code.
  • Sample code: MoveParagraph
    V2 CTP1 sample code.
  • Sample code: RetrieveContentInCustomXmlBlock
    V2 CTP1 sample code.
  • Sample code: RetrieveSdtContentInDocx
    V2 CTP1 sample code.
  • Sample code: SetFontToTextUnitInPresentation
    V2 CTP1 sample code.
  • Sample code: EnumerateExternalHyperlinksInWord
    V2 CTP1 sample code.
  • Sample code: SetRunFormatting
    V2 CTP1 sample code.
  • Sample code: SetParagraphFormatting
    V2 CTP1 sample code.
  • Sample code: ReplaceImage
    V2 CTP1 sample code.
  • Sample code: ClearParagraphDirectFormatting
    V2 CTP1 sample code.
  • Sample code: GetTextInParagraph
    V2 CTP1 sample code.
  • Sample code: GetParagraphsInSection
    V2 CTP1 sample code.
  • Sample code: DeleteSpreadsheetCellContent
    V2 CTP1 sample code.
  • Sample code: ListWorksheets
    V2 CTP1 sample code.
  • Sample code: SetShapeColor
    V2 CTP1 sample code.
  • Sample code: CreateWordMLDocument
    V2 CTP1 sample code.
  • Learning Resources for Open XML SDK
    This article lists all kinds of resources for Open XML Standard and SDK learners.
  • Open XML SDK V2 Overview
    Open XML SDK V2 Overview
  • Surveys
    Introduction to the active surveys on the homepage.
  • Yazı kategorisi: Open XML | » yorum bırak;