In this article I will explain with an example, how to dynamically create and download
Word document using
OpenXml in ASP.Net with C# and VB.Net.
Install DocumentFormat.OpenXml package
HTML Markup
The HTML Markup consists of following control:
Button – For creating Word document.
The Button has been assigned with an OnClick event handler.
<asp:Button Text="Create Document" runat="server" OnClick="OnCreate" />
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using FontSize = DocumentFormat.OpenXml.Wordprocessing.FontSize;
VB.Net
Imports System.IO
Imports DocumentFormat.OpenXml
Imports DocumentFormat.OpenXml.Packaging
Imports DocumentFormat.OpenXml.Wordprocessing
Imports FontSize = DocumentFormat.OpenXml.Wordprocessing.FontSize
Using OpenXml Word Processing functions
Below there are two functions which are simplified in order to add Words with styles and HyperLinks.
AddRun – This function is used to add words to the document.
Inside this method, the text content to be added to the Document is created.
The AddRun function accepts the following parameters:
1. word – The text content to be added to the document.
2. font – Default value Arial. It specifies the Font of the text.
3. size – Default value 20. It specifies the Font Size of the text.
4. bold – Default value false. It specifies the text will have BOLD style.
5. italic – Default value false. It specifies the text will have ITALIC style.
6. underline – Default value false. It specifies the text will have UNDERLINE style.
7. preserveSpace – Default value true. It preserves the space before and after the text.
Inside this method, an object of Run class is created and using RunFonts and FontSize classes, the size of the text content is defined.
After that, using RunProperties, the styles are applied to the text content PreserveSpace value is also set using Preserve property of the SpaceProcessingModeValues class.
Finally, the Run class object is returned.
C#
private Run AddRun(
string word,
string font = "Arial",
string size = "20",
bool bold = false,
bool italic = false,
bool underline = false,
bool preserveSpace = true)
{
// Create Run instance.
Run run = new Run();
// Create RunFonts instance.
RunFonts runFont = new RunFonts { Ascii = font };
// Create FontSize instance.
//It must be multiplication twice of the required size.
FontSize fontSize = new FontSize { Val = new StringValue(size) };
// Create Text instance.
Text text = new Text(word);
// Create RunProperties instance.
RunProperties runProperties = new RunProperties();
if (bold)
{
// Applying Bold.
runProperties.Bold = new Bold();
}
if (italic)
{
// Applying Italic.
runProperties.Italic = new Italic();
}
if (underline)
{
// Applying Underline.
runProperties.Underline = new Underline { Val = UnderlineValues.Single };
}
if (preserveSpace)
{
// Defines the SpaceProcessingModeValues.
text.Space = SpaceProcessingModeValues.Preserve;
}
}
// Adding Font to RunProperties.
runProperties.Append(runFont);
// Adding FontSize to RunProperties.
runProperties.Append(fontSize);
// Adding RunProperties to Run.
run.Append(runProperties);
// Adding Text to Run.
run.Append(text);
return run;
}
VB.Net
Private Function AddRun(word As String,
Optional font As String = "Arial",
Optional size As String = "20",
Optional bold As Boolean = False,
Optional italic As Boolean = False,
Optional underline As Boolean = False,
Optional preserveSpace As Boolean = True) As Run
' Create Run instance.
Dim run As New Run()
' Create RunFonts instance.
Dim runFont As New RunFonts() With {.Ascii = font}
' Create FontSize instance.
' It must be multiplication twice of the required size.
Dim fontSize As New FontSize() With {.Val = New StringValue(size)}
' Create Text instance.
Dim text As New Text(word)
' Create RunProperties instance.
Dim runProperties As New RunProperties()
If bold Then
' Applying Bold.
runProperties.Bold = New Bold()
End If
If italic Then
' Applying Italic.
runProperties.Italic = New Italic()
End If
If underline Then
' Applying Underline.
runProperties.Underline = New Underline() With {.Val = UnderlineValues.Single}
End If
If preserveSpace Then
' Defines the SpaceProcessingModeValues.
text.Space = SpaceProcessingModeValues.Preserve
End If
' Adding Font to RunProperties.
runProperties.Append(runFont)
' Adding FontSize to RunProperties.
runProperties.Append(fontSize)
' Adding RunProperties to Run.
run.Append(runProperties)
' Adding Text to Run.
run.Append(text)
Return run
End Function
AddLink –This function is used to create HyperLink to be added to the Document.
The AddLink function accepts the following parameters:
1. MainDocumentPart – The Document to which the HyperLink will be added.
2. text – The text to which the HyperLink will be set.
3. url – The URL which will be opened on click of HyperLink.
Inside this method, an object of HyperLink class is created and necessary properties i.e. Id and History are set.
Then, Run class object is created using AddRun method (explained earlier) and the properties i.e. Color, RunStyle and Underline are set and appended to HyperLink class object.
Finally, the HyperLink class object is returned.
C#
private Hyperlink AddLink(ref MainDocumentPart mainPart, string text, string url)
{
// Adding HyperlinkRelationship with Relationship Id.
HyperlinkRelationship hyperlinkRelationship = mainPart.AddHyperlinkRelationship(new Uri(url), true);
// Creating Hyperlink.
Hyperlink hyperlink = new Hyperlink();
hyperlink.Id = hyperlinkRelationship.Id;
// Add to Viewed Hyperlinks.
hyperlink.History = OnOffValue.FromBoolean(true);
// Creating Run.
Run run = this.AddRun(text, underline: true);
// Specifying the Color Class.
run.RunProperties.Color = new Color { ThemeColor = ThemeColorValues.Hyperlink };
// Specifying the RunStyle Class.
run.RunProperties.RunStyle = new RunStyle { Val = "Hyperlink" };
// Underline the Hyperlink.
run.RunProperties.Underline = new Underline { Val = UnderlineValues.Single };
// Adding the Run to Hyperlink.
hyperlink.Append(run);
return hyperlink;
}
VB.Net
Private Function AddLink(ByRef mainPart As MainDocumentPart, text As String, url As String) As Hyperlink
' Adding HyperlinkRelationship with Relationship Id.
Dim hyperlinkRelationship As HyperlinkRelationship = mainPart.AddHyperlinkRelationship(New Uri(url), True)
' Creating Hyperlink.
Dim hyperlink As New Hyperlink()
hyperlink.Id = hyperlinkRelationship.Id
' Add to Viewed Hyperlinks.
hyperlink.History = OnOffValue.FromBoolean(True)
' Creating Run.
Dim run As Run = Me.AddRun(text, underline:=True)
' Specifying the Color Class.
run.RunProperties.Color = New Color() With {.ThemeColor = ThemeColorValues.Hyperlink}
' Specifying the RunStyle Class.
run.RunProperties.RunStyle = New RunStyle() With {.Val = "Hyperlink"}
' Underline the Hyperlink.
run.RunProperties.Underline = New Underline() With {.Val = UnderlineValues.Single}
' Adding the Run to Hyperlink.
hyperlink.Append(run)
Return hyperlink
End Function
Creating Word Document Dynamically in C# and VB.Ne
When theCreate Document Button is clicked, an object of WordprocessingDocument is created.
Then, document structure is designed and text contents and link text are added to document using AddRun method (explained earlier) and AddLink (explained earlier) method respectively.
Finally, the Response class properties are set.
1. Content-Disposition – It is a response header indicating, the download file is an attachment and allows setting the file name.
2. ContentType – It is called MIME Type. It informs the Browser about the file type. In this case it is Word document.
C#
protected void OnCreate(object sender, EventArgs e)
{
using (MemoryStream stream = new MemoryStream())
{
// Create a document.
using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, true))
{
// Add main document part.
MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();
// Create document structure.
mainPart.Document = new Document();
// Create document body.
Body body = mainPart.Document.AppendChild(new Body());
// Create paragraph.
Paragraph paragraph = new Paragraph();
// Creating Run.
Run run = this.AddRun("Hi,");
// Adding Run to Paragraph.
paragraph.Append(run);
// Adding Paragraph to Body.
body.Append(paragraph);
// Adding new Paragraph.
paragraph = new Paragraph();
run = this.AddRun("This is ");
paragraph.Append(run);
// Adding Text with Bold and Italic.
run = this.AddRun("Mudassar Khan", bold: true, italic: true);
paragraph.Append(run);
run = this.AddRun(".");
paragraph.Append(run);
// Adding Paragraph to Body.
body.Append(paragraph);
// Adding Paragraph for Hyperlink.
paragraph = new Paragraph();
// Adding Hyperlink to Paragraph.
paragraph.Append(this.AddLink(ref mainPart, "aspsnippets", "https://www.aspsnippets.com"));
// Adding Hyperlink Paragraph to Document Body.
body.Append(paragraph);
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
Response.AppendHeader("Content-Disposition", "attachment;filename=Sample.docx");
Response.BinaryWrite(stream.ToArray());
Response.Flush();
Response.End();
}
}
VB.Net
Protected Sub OnCreate(sender As Object, e As EventArgs)
Using stream As New MemoryStream()
' Create a document.
Using wordDocument As WordprocessingDocument = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document, True)
' Add main document part.
Dim mainPart As MainDocumentPart = wordDocument.AddMainDocumentPart()
' Create document structure.
mainPart.Document = New Document()
' Create document body.
Dim body As Body = mainPart.Document.AppendChild(New Body())
' Create paragraph.
Dim paragraph As New Paragraph()
' Creating Run.
Dim run As Run = Me.AddRun("Hi,")
' Adding Run to Paragraph.
paragraph.Append(run)
' Adding Paragraph to Body.
body.Append(paragraph)
' Adding new Paragraph.
paragraph = New Paragraph()
run = Me.AddRun("This is ")
paragraph.Append(run)
' Adding Text with Bold and Italic.
run = Me.AddRun("Mudassar Khan", bold:=True, italic:=True)
paragraph.Append(run)
run = Me.AddRun(".")
paragraph.Append(run)
' Adding Paragraph to Body.
body.Append(paragraph)
' Adding Paragraph for Hyperlink.
paragraph = New Paragraph()
' Adding Hyperlink to Paragraph.
paragraph.Append(Me.AddLink(mainPart, "aspsnippets", "https://www.aspsnippets.com"))
' Adding Hyperlink Paragraph to Document Body.
body.Append(paragraph)
End Using
Response.Clear()
Response.Buffer = True
Response.Charset = ""
Response.ContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
Response.AppendHeader("Content-Disposition", "attachment;filename=Sample.docx")
Response.BinaryWrite(stream.ToArray())
Response.Flush()
Response.End()
End Using
End Sub
Screenshot
Demo
Downloads