Implementation environment: Visual Studio 2010 and OpenXml SDK 2.0
[Csharp]
Using System;
Using System. Collections. Generic;
Using System. ComponentModel;
Using System. Data;
Using System. Drawing;
Using System. Linq;
Using System. Text;
Using System. Windows. Forms;
Using DocumentFormat. OpenXml. Packaging;
Using DocumentFormat. OpenXml. Wordprocessing;
Namespace OpenXmlWordSdtBlock
{
Public partial class Form1: Form
{
Public Form1 ()
{
InitializeComponent ();
}
Private void button#click (object sender, EventArgs e)
{
OpenFileDialog objOpenFileDialog = new OpenFileDialog ();
ObjOpenFileDialog. Filter = "Word Document (*. docx) | *. docx ";
ObjOpenFileDialog. ShowDialog ();
String strPath = objOpenFileDialog. FileName;
Form2 objForm2 = new Form2 ();
ObjForm2.ShowDialog ();
String strInsertText = objForm2.Msg;
If (strPath. Length> 0)
{
Try
{
Using (WordprocessingDocument objWordprocessingDocument =
WordprocessingDocument. Open (strPath, true ))
{
/*
* The following code obtains MainDocumentPart, Document, and Body.
* These are existing structures in Word documents, so no New is needed.
*/
MainDocumentPart objMainDocumentPart =
ObjWordprocessingDocument. MainDocumentPart;
Document objDocument = objMainDocumentPart. Document;
Body objBody = objDocument. Descendants <Body> ()
. FirstOrDefault ();
/*
* The following Code creates a new section to put Rich Text Content
* Control. In fact, all Content Control is in the OpenXml format.
* All are represented by SdtBlock. So this is to insert a Plain Text
* Content Control is also true.
*/
Paragraph objParagraph_1 = new Paragraph ();
SdtBlock objSdtBlock = new SdtBlock ();
SdtContentBlock objSdtContentBlock =
New SdtContentBlock ();
Paragraph objparagraph2 = new Paragraph ();
Run objRun = new Run ();
Text objText = new Text ();
If (strInsertText. Length> 0)
ObjText. Text = strInsertText;
Else
ObjText. Text = "<Null> ";
ObjRun. Append (objText );
ObjParagraph_2.Append (objRun );
ObjSdtContentBlock. Append (objparagraph2 );
ObjSdtBlock. Append (objSdtContentBlock );
ObjParagraph_1.Append (objSdtBlock );
ObjBody. Append (objParagraph_1 );
ObjDocument. Save ();
}
}
Catch (Exception ex)
{
MessageBox. Show (string. Format
("Stack: \ n {0} \ nException: \ n {1}", ex. StackTrace,
Ex. Message), "OpenxXmlWordSdtBlock Exception ");
}
}
}
}
}
From TX_OfficeDev's column