Click here to Skip to main content
15,891,902 members
Articles / Programming Languages / C#

Creating a Word Document by Passing the Dataset including Image(s)

Rate me:
Please Sign up or sign in to vote.
2.60/5 (5 votes)
30 Aug 2007CPOL2 min read 37.4K   995   29   2
Create a Word document via dataset and merge fields in Word (C#)

Introduction

Create a Word document by passing a dataset (C#, Office 2003 any datasource).

Background

Creating a Word document with merge fields, dataset and some images to go with can be a tedious task. This code does the job for you. Just add this to a project and use. More details are given below.

Using the Code

This code was developed for a specific use in our organization and it depends entirely on developers how they want to develop it further and use it in their project. The attached code is a .cs file where the main document generation is placed.

Add this file to a project.

Make sure you have installed and added reference to Office Runtime (VSTO) and Microsoft Word library.

Create a Word template with few merge fields. (Make sure the merge field names are the same as the names of the dataset field name you provide to the code).

If you want an image to be embedded in the document, that should also be part of the dataset (of course as Byte array).

Now for the image merge fields in Word template should be inserted something like this. E.g. <<UserSignature(image(270,70))>> (Play around with this and you will get the desired width and height).

Here UserSignature is the dataset field name, image is needed as in the example above, 270 and 70 are width and height respectively.

Calling the Code

C#
//
// 
ABCCustomDocuments myDoc = new ABCCustomDocuments();
bool bDocGen = myDoc.CreateWordDocument(sTemplate, savedDocsPath + sFilename, ds);
  • sTemplate is the template file with complete folder path.
  • savedDocsPath is the Path for the folder where you want to store the document.
  • sFilename is the name of the file you want to be saved as.
  • ds is a single row dataset with required column values including the image.
C#
if (bDocGen == true)
{
//If you are using ASP.NET, you can send the document back to client like this./
Response.ContentType = "application/msword";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.TransmitFile(savedDocsPath + sFilename);
Response.End();
}
//

Guidelines are provided for you. Feel free to use this code and develop further and share with the community.

Points of Interest

Hope this is of some help to someone out there?

History

  • 30th August, 2007: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAnother DOCX mail merge solution Pin
Johnny Glenn14-Mar-12 0:10
Johnny Glenn14-Mar-12 0:10 
Hi,

to .NET Word mail merge DataTable to C# DOCX file you can also try this C# / VB.NET Word library.

Here is a sample code how to do mail merge with DataTable with image support:
C#
// Use the component in free mode.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");

// Define DataTable with two columns: 'FullName' and 'PicturePath', and fill it with some data.
// You don't have to do this if you already have a DataTable instance.
var dataTable = new DataTable("People")
{
  Columns =
  {
    new DataColumn("FullName", typeof(string)),
    new DataColumn("PicturePath", typeof(string))
  },
  Rows =
  {
    new object[] { "John Doe", "john-doe.png" },
    new object[] { "Fred Nurk", "fred-nurk.png" },
    new object[] { "Hans Meier", "hans-meier.png" },
    new object[] { "Ivan Horvat", "ivan-horvat.png" }
  }
};

// Create and save a template document. 
// You don't have to do this if you already have a template document.
// This code is only provided as a reference how template document should look like.
var document = new DocumentModel();
document.Sections.Add(
  new Section(document,
    new Table(document,
      new TableRow(document,
        new TableCell(document,
          new Paragraph(document, "Full Name")),
        new TableCell(document,
          new Paragraph(document, "Picture"))),
      new TableRow(document,
        new TableCell(document,
          new Paragraph(document,
            new Field(document, FieldType.MergeField, "RangeStart:People"),
            new Field(document, FieldType.MergeField, "FullName"))),
        new TableCell(document,
          new Paragraph(document,
            new Field(document, FieldType.MergeField, "PicturePath"),
            new Field(document, FieldType.MergeField, "RangeEnd:People")))))));
document.Save("TemplateDocument.docx", SaveOptions.DocxDefault);

// Load a template document.
document = DocumentModel.Load("TemplateDocument.docx", LoadOptions.DocxDefault);

// Customize mail merge - PicturePath field will be replaced by Picture.
document.MailMerge.FieldMerging += (sender, e) =>
{
  if (e.FieldName == "PicturePath")
    e.Inline = new Picture(document, (string)e.Value);
};

// Mail merge template document with DataTable.
// Important: DataTable.TableName and RangeStart/RangeEnd merge field names must match.
document.MailMerge.ExecuteRange(dataTable);

// Save the mail merged document.
document.Save("Document.docx", SaveOptions.DocxDefault);

QuestionRead Word Document To Dataset Pin
majid soorani4-Sep-07 11:54
majid soorani4-Sep-07 11:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.