This example demonstrates how to write a simple text to a Word document.
This simple example creates 'Hello World' text and save to a Word document. Its support multiple word extension files. Below are supported file formats
- DOC (.doc)
- DOCX (.docx)
- RTF (.rtf)
- TEXT (.txt)
- Word XML
- E-book (.epub)
- DSL based XML
- HTML
On clicking generate button, it will create a Word document in the selected format.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Text;
using OfficeComponent.Word;
namespace OfficeComponent.Samples
{
class HelloWorldExample : WordExampleBase
{
public HelloWorldExample(string commonDataPath, string outputDir)
: base(commonDataPath, outputDir)
{
}
public HelloWorldExample(string commonDataPath, string outputDir, string xmlFile) : base(commonDataPath, outputDir, xmlFile)
{
}
public override string Execute()
{
// Create a new instance of WordDocument class.
WordDocument document = new WordDocument();
// Add a new section to the document.
Section section = document.AddSection();
// Adding a new paragraph to the section.
Paragraph paragraph = section.AddParagraph();
// Insert Text into the paragraph
paragraph.AppendText("OfficeComponent Word - Hello World!");
string fileName = Path.Combine(OutputDir, this.GetType().Name + "_" + Guid.NewGuid().ToString() + GetExtension(SaveAsFormat));
// Save the document.
document.Save(fileName, SaveAsFormat);
// Close the document.
document.Close();
// return the generate file path.
return fileName;
}
}
}
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text
Imports OfficeComponent.Word
Namespace OfficeComponent.Samples
Friend Class HelloWorldExample
Inherits WordExampleBase
Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
MyBase.New(commonDataPath, outputDir)
End Sub
Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
MyBase.New(commonDataPath, outputDir, xmlFile)
End Sub
Public Overrides Function Execute() As String
' Create a new instance of WordDocument class.
Dim document As New WordDocument()
' Add a new section to the document.
Dim section As Section = document.AddSection()
' Adding a new paragraph to the section.
Dim paragraph As Paragraph = section.AddParagraph()
' Insert Text into the paragraph
paragraph.AppendText("OfficeComponent Word - Hello World!")
Dim fileName As String = Path.Combine(OutputDir, Me.GetType().Name & "_" & Guid.NewGuid().ToString() & GetExtension(SaveAsFormat))
' Save the document.
document.Save(fileName, SaveAsFormat)
' Close the document.
document.Close()
' return the generate file path.
Return fileName
End Function
End Class
End Namespace