Message-ID: <583516210.8337.1711642758937.JavaMail.web05$@web05> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_8336_1974385722.1711642758937" ------=_Part_8336_1974385722.1711642758937 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: file:///C:/exported.html Product Catalog Sample

Product Catalog Sample

Intro

An AdventureWorks P= roduct Catalog with formatting, tables, lists, nested data, and images.

Create a product catalog by writing data into sections of an existing Wo= rd document. This sample demonstrates writing data from a database, formatt= ing, nested Word lists, Word tables, and image insertion

Code

=20
 private WordApplication wwapp;
private Document doc;
private Font charFormat;
// The three major product categories 
string[] categories =3D { "Component", "Clothing", &quo=
t;Accessory" };
private bool bCategoriesOnNewPage =3D true;
// This DataTable will store all the product details 
private DataTable data;

/// <summary>
/// Build the report with WordTemplate
/// </summary>
public void GenerateDocument()
{       
 // Create an instance of WordApplication and open the template document&nb=
sp;
 wwapp =3D new WordApplication();

 string templatePath =3D @"..\..\WordTemplateFiles\ProductCatalogTempl=
ate.doc";
 doc =3D wwapp.Open(templatePath);

 // This document has three existing sections.
 // The title page, the welcome letter page, and the 
 // blank section where the catalog items should be started.

 Section secTitlePg =3D doc.Sections[0];
 Section secWelcomePg =3D doc.Sections[1];
 Section secCatalogPg =3D doc.Sections[2];

 // Get a reference to the base style and set up a CharacterFormat
 // object for use throughout this class.

 NamedStyle baseStyle =3D doc.Styles[NamedStyle.BuiltIn.Normal];
 charFormat =3D baseStyle.Font;
 charFormat.FontName =3D "Arial";

 // Add the current date to the first section 
 AddGeneratedDate(secTitlePg);

 // Add a bulleted list to the second section.
 // Bulleted items will be numbered.

 AddList(secWelcomePg, true);
 // Add the catalog items to the third section 

 // Populate data DataTable
  // GetCSVData() is a helper method for parsing .csv files
  
 data =3D GetCSVData(@"..\..\WordData\ProductCatalog2.csv");

 AddCatalog(secCatalogPg);

 // Save the document by streaming it to the client's browser 
 wwapp.Save(doc, @"..\..\WordOutputFiles\ProductCatalog_out.doc")=
;
}


/// <summary>
/// Add the date string to the provided Range.
/// Date will be written in the form: "Jan 1, 2009"
/// </summary>
/// <param name=3D"rng">Element into which the date should =
be written</param>
private void AddGeneratedDate(Element rng)
{
 DateTime dt =3D DateTime.Now;
 string datestring =3D String.Format("{0}/{1}/{2}", dt.Month, dt.=
Day, dt.Year);
 rng.InsertTextAfter(datestring, false);
}

/// <summary>
/// Add the bulleted list of requested categories 
/// and subcategories to the provided Range.  
/// </summary>
/// <param name=3D"rng">Element into which the list should =
be written</param>
/// <param name=3D"bNumbered">Numbered (ordered) list</p=
aram>
private void AddList(Element rng, bool bNumbered)
{
 // Add line breaks 
 rng.InsertParagraphAfter(null);
 rng.InsertParagraphAfter(null);

 // Create the List 
 List list =3D rng.InsertListAfter(bNumbered);

 // Loop for every selected category 
 for (int iCat =3D 0; iCat < categories.Length; iCat++)
 {
 // Add the category text to the first level of the outline.
 // Make the font bold-faced.

 CharacterRun categoryRun =3D
 list.AddEntry(0).InsertTextAfter(categories[iCat], charFormat);
 categoryRun.Font.Bold =3D true;

 // Get a list of product subcategories from the major
 // category name.

 string[] subCats =3D GetProductSubCategories(categories[iCat]);

 // Loop for every subcategory in the current category 
 for (int iSubCat =3D 0; iSubCat < subCats.Length; iSubCat++)
 {
 // Add the subcategory text to the second
 // level of the outline.

 ListEntry li =3D list.AddEntry(1);

 //li.LineNumberingAllowed =3D true;
 li.InsertTextAfter(subCats[iSubCat], charFormat);
 } // for each subcategory
 } // for each category
}

/// <summary>
/// Add the main product catalog to the provided Range.
/// </summary>
/// <param name=3D"rng">Element into which the catalog will=
 be written</param>
private void AddCatalog(Element rng)
{   
 // Loop for every major category chosen 
 for (int iCat =3D 0; iCat < categories.Length; iCat++)
 {
 // Get the category name from the array categories 
 string catName =3D categories[iCat];

 // Insert a table 1row x 1col. This table will 
 // hold the header text for every major category.

 Table catTbl =3D doc.InsertTableAfter(1, 1);

 // Write the major category name into the table cell.
 // Set cell background and font appearance.

 CharacterRun catRun =3D
 catTbl[0, 0].InsertTextAfter(catName, charFormat);
 catTbl[0, 0].Shading.BackgroundColor =3D System.Drawing.Color.Gray;
 catRun.Font.Bold =3D true;
 catRun.Font.Italic =3D true;
 catRun.Font.FontSize =3D 26.0f;

 // Get subcategory names for the current category 
 string[] subCats =3D GetProductSubCategories(catName);
// Marker

//                // Loop once for =
every subcategory in the current category 
 for (int iSubCat =3D 0; iSubCat < subCats.Length; iSubCat++)
 {
 doc.InsertParagraphAfter(null);
 string subCat =3D subCats[iSubCat];

 // Insert a smaller header for the subcategory 
 CharacterRun subCatRun =3D
 doc.InsertParagraphAfter(null).InsertTextAfter(subCat, charFormat);
 subCatRun.Font.Bold =3D true;
 subCatRun.Font.FontSize =3D 22.0f;
// GetProductCatalogData
 // Get a list of products in the current subcategory 
 DataTable dtProducts =3D GetProductCatalogData(subCat);


 // Loop for every product in the subcategory 
 //REFINE THIS COMMENT
 foreach (DataRow dr in dtProducts.Rows)
 {
 // Insert a table to hold product data 
 Table prodTbl =3D doc.InsertTableAfter(4, 2);

 // Merge the top row of cells 
 prodTbl[0, 0].FirstMerged =3D true;
 prodTbl[0, 1].Merged =3D true;

 // Add the product name and set font appearance 
 CharacterRun titleRun =3D
 prodTbl[0, 0].InsertTextAfter(dr["Name"].ToString(), charFormat)=
;
 titleRun.Font.FontSize =3D 18.0f;
 titleRun.Font.Bold =3D true;
 titleRun.Font.Italic =3D true;
 titleRun.Font.TextColor =3D System.Drawing.Color.Blue;

 // Add product description to the next row 
 prodTbl[1, 0].InsertTextAfter(dr["Description"].ToString(), char=
Format);

 // InsertImageAfter method 
 if (dr["ThumbNailPhoto"].ToString() !=3D "")
 {
 InlineImage image =3D prodTbl[1, 1].InsertImageAfter(@"..\..\WordImag=
es\ProductCatalogImages\" + dtProducts.Rows[dtProducts.Rows.IndexOf(dr=
)]["ThumbNailPhoto"]);
 double width =3D image.Width;
 double height =3D image.Height;
 Console.WriteLine("W: " + image.Width + ", H: " + imag=
e.Height);

 image.Height=3D(int)( height//(2000 / width));
 image.Width=3D2000;

 Console.WriteLine("W: "+image.Width+", H: "+image.Heig=
ht);
 }

 // Write the rest of the product details into the table 
 prodTbl[2, 0].InsertTextAfter("Product Number", charFormat).Font=
.Bold =3D true;
 prodTbl[3, 0].InsertTextAfter(dr["ProductNumber"].ToString(), ch=
arFormat);
 prodTbl[2, 1].InsertTextAfter("Price", charFormat).Font.Bold =3D=
 true;
 prodTbl[3, 1].InsertTextAfter("$" + dr["Price"].ToStri=
ng(), charFormat);
    
   }

    }

 // If it was chosen to put categories on new pages,
 // AND if the last category hasn't just been written,
 // add a section/page break.

 if (bCategoriesOnNewPage && (iCat < categories.Length - 1))
 {
 Section sec =3D doc.CreateSectionAfter();
 sec.Break =3D Section.BreakType.Page;
 }
 }
}

/// <summary>
/// Set document property metadata for the catalog document
/// </summary>
private void AddDocProperties()
{
 // Get the DocumentProperties interface from Document 
 DocumentProperties docprops =3D doc.DocumentProperties;

 // Set built-in DocumentProperties values 
 docprops.Author =3D "John Doe";
 docprops.Comments =3D "A basic demonstration of OfficeWriter for Word=
";
 docprops.Company =3D "SoftArtisans, Inc.";
 docprops.Title =3D "Basic Word Document";

 // Set custom DocumentProperties key/value pairs 
 docprops.SetCustomProperty("GeneratedBy", "SoftArtisans Off=
iceWriter for Word");
}

/// <summary>
/// Get a list of products for a subcategory.
/// </summary>
/// <param name=3D"subCat">Subcategory name to look up</=
param>
/// <returns>DataTable of product from the provided subcategory</r=
eturns>
private DataTable GetProductCatalogData(string subCat)
{
 DataTable dt =3D new DataTable();
 dt.Columns.Add("Name");
 dt.Columns.Add("Description");
 dt.Columns.Add("ProductNumber");
 dt.Columns.Add("Price");
 dt.Columns.Add("ThumbNailPhoto");

 //find data
 int iRow =3D 0;
 while (iRow < data.Rows.Count)
 {
 if (data.Rows[iRow]["Subcategory"].ToString() =3D=3D subCat)
 {
 dt.ImportRow(data.Rows[iRow]);
 }
 iRow++;
 }
 return dt;
}

/// <summary>
/// Get a list of subcategory names for the provided major category.
/// </summary>
/// <param name=3D"cat">Category to look up</param>
/// <returns>Array of product subcategory strings</returns>
private string[] GetProductSubCategories(string cat)
{
 ArrayList al =3D new ArrayList();
 if (cat =3D=3D "Clothing")
 {
 al.AddRange(new string[]{"Bib-Shorts","Caps","Glo=
ves","Jerseys","Shorts","Socks","Ti=
ghts","Vests"});
 }
 if (cat =3D=3D "Component")
 {
 al.AddRange(new string[]{"Handlebars","Bottom Brackets"=
;,"Brakes","Chains","Cranksets","Deraill=
eurs","Forks","Headsets","Mountain Frames&quo=
t;,"Pedals","Road Frames","Saddles","Tou=
ring Frames","Wheels"});

 }
 if (cat =3D=3D "Accessory")
 {
 al.AddRange(new string[]{ "Bike Racks","Bike Stands",&=
quot;Bottles and Cages","Cleaner","Fenders","=
Helmets","Hydration Packs","Lights","Locks&qu=
ot;,"Panniers","Pumps","Tires and Tubes"});
 }
 return (string[])al.ToArray(typeof(string));
}
#region Utility Methods
//Uses CSV reader
System.Data.DataTable GetCSVData(string csvFileName)
{
 DataTable dt;
 using (GenericParserAdapter parser =3D new GenericParserAdapter(csvFileNam=
e))
 {
 parser.ColumnDelimiter =3D ',';
 parser.FirstRowHasHeader =3D true;
 dt =3D parser.GetDataTable();
 }
 return dt;
}

#endregion

=20

Downloads

Template: P= roductCatalogTemplate.doc

Output: Product= Catalog_out.doc

------=_Part_8336_1974385722.1711642758937--