DotNet Export To Word Or Html Code Sample

This is the helper class…


using System;
using System.Text;
using System.Web;

namespace Test.Framework.Common.Core
{
	/// 
	/// This is global utility class that helps with some common Word-based functionality.
	/// 
	public sealed class WordHelper
	{
		#region MemberConsts

		public const int InnerHtmlLengthMin = 0;
		public static readonly int InnerHtmlLengthMax = int.MaxValue;
		public const double DefaultDouble = double.MinValue;
		public const Test.Framework.Common.Core.WordHelper.FileExtension DefaultFileExtension = Test.Framework.Common.Core.WordHelper.FileExtension.DOC;
		public const Test.Framework.Common.Core.WordHelper.PageOrientation DefaultPageOrientation = Test.Framework.Common.Core.WordHelper.PageOrientation.Portrait;
		public const Test.Framework.Common.Core.WordHelper.PageMarginInInches DefaultPageMarginInInches = Test.Framework.Common.Core.WordHelper.PageMarginInInches._0_POINT_5_;

		#endregion //MemberConsts

		#region MemberEnums

		public enum FileExtension
		{
			HTM,
			DOC
		}

		public enum PageOrientation
		{
			Landscape,
			Portrait
		}

		public enum PageMarginInInches
		{
			_0_POINT_5_,
			_1_POINT_0_,
			_1_POINT_5_,
			_2_POINT_0_
		}

		#endregion //MemberEnums

		#region ConversionHelpers

		public static Test.Framework.Common.Core.WordHelper.PageOrientation ConvertToPageOrientationByForce(string targetOrientation)
		{
			Test.Framework.Common.Core.WordHelper.PageOrientation myOrientation = Test.Framework.Common.Core.WordHelper.DefaultPageOrientation;

			try
			{
				targetOrientation = (targetOrientation + "").Trim().ToLower();

				if (targetOrientation == Test.Framework.Common.Core.WordHelper.PageOrientation.Landscape.ToString().ToLower())
				{
					myOrientation = Test.Framework.Common.Core.WordHelper.PageOrientation.Landscape;
				}
				else if (targetOrientation == Test.Framework.Common.Core.WordHelper.PageOrientation.Portrait.ToString().ToLower())
				{
					myOrientation = Test.Framework.Common.Core.WordHelper.PageOrientation.Portrait;
				}
				else
				{
					myOrientation = Test.Framework.Common.Core.WordHelper.DefaultPageOrientation;
				}
			}
			catch 
			{
				myOrientation = Test.Framework.Common.Core.WordHelper.DefaultPageOrientation;
			}

			return myOrientation;
		}

		public static Test.Framework.Common.Core.WordHelper.PageMarginInInches ConvertToPageMarginInInchesByForce(string targetPageMarginInInches)
		{
			Test.Framework.Common.Core.WordHelper.PageMarginInInches myPageMarginInInches = Test.Framework.Common.Core.WordHelper.DefaultPageMarginInInches;

			try
			{
				targetPageMarginInInches = (targetPageMarginInInches + "").Trim().ToLower();
				double myPageMarginInInchesAsDouble = Test.Framework.Common.Core.WordHelper.ConvertToDoubleByForce(targetPageMarginInInches);

				if (myPageMarginInInchesAsDouble == 
					Test.Framework.Common.Core.WordHelper.ConvertToDoubleByForce(Test.Framework.Common.Core.WordHelper.PageMarginInInches._0_POINT_5_))
				{
					myPageMarginInInches = Test.Framework.Common.Core.WordHelper.PageMarginInInches._0_POINT_5_;
				}
				else if (myPageMarginInInchesAsDouble == 
					Test.Framework.Common.Core.WordHelper.ConvertToDoubleByForce(Test.Framework.Common.Core.WordHelper.PageMarginInInches._1_POINT_0_))
				{
					myPageMarginInInches = Test.Framework.Common.Core.WordHelper.PageMarginInInches._1_POINT_0_;
				}
				else if (myPageMarginInInchesAsDouble == 
					Test.Framework.Common.Core.WordHelper.ConvertToDoubleByForce(Test.Framework.Common.Core.WordHelper.PageMarginInInches._1_POINT_5_))
				{
					myPageMarginInInches = Test.Framework.Common.Core.WordHelper.PageMarginInInches._1_POINT_5_;
				}
				else if (myPageMarginInInchesAsDouble == 
					Test.Framework.Common.Core.WordHelper.ConvertToDoubleByForce(Test.Framework.Common.Core.WordHelper.PageMarginInInches._2_POINT_0_))
				{
					myPageMarginInInches = Test.Framework.Common.Core.WordHelper.PageMarginInInches._2_POINT_0_;
				}
				else
				{
					myPageMarginInInches = Test.Framework.Common.Core.WordHelper.DefaultPageMarginInInches;
				}
			}
			catch
			{
				myPageMarginInInches = Test.Framework.Common.Core.WordHelper.DefaultPageMarginInInches;
			}

			return myPageMarginInInches;
		}

		public static double ConvertToDoubleByForce(Test.Framework.Common.Core.WordHelper.PageMarginInInches targetValue)
		{
			double myDouble = Test.Framework.Common.Core.WordHelper.DefaultDouble;

			try
			{
				string myInputAsString = targetValue.ToString().ToLower();
				myInputAsString = myInputAsString.Replace("point", ".");
				myInputAsString = myInputAsString.Replace("_", "");

				//Call a helper.
				myDouble = Test.Framework.Common.Core.WordHelper.ConvertToDoubleByForce(myInputAsString);
			}
			catch
			{
				myDouble = Test.Framework.Common.Core.WordHelper.DefaultDouble;
			}

			return myDouble;
		}

		public static double ConvertToDoubleByForce(string targetValue)
		{
			double myDouble = Test.Framework.Common.Core.WordHelper.DefaultDouble;

			try
			{
				targetValue = (targetValue + "").Trim().ToLower();
				myDouble = Convert.ToDouble(targetValue);
			}
			catch
			{
				myDouble = Test.Framework.Common.Core.WordHelper.DefaultDouble;
			}

			return myDouble;
		}

		#endregion //ConversionHelpers

		#region Helpers

		public static bool IsDouble(string targetText)
		{
			bool isDoubleFlag = false;

			try
			{
				targetText = (targetText + "").Trim().ToLower();
				double myTemp = Convert.ToDouble(targetText);
				isDoubleFlag = true;
			}
			catch
			{
				isDoubleFlag = false;
			}

			return isDoubleFlag;
		}

		private static string GetHtmlPrefix(WordHelper.PageOrientation targetOrientation, WordHelper.PageMarginInInches pageMargins)
		{
			string myPrefix = "";

			StringBuilder myBuilder = new StringBuilder();

			myBuilder.AppendLine(" ");

			myBuilder.AppendLine(" ");
			myBuilder.AppendLine("EXPORT ");
			myBuilder.AppendLine(@" ");
			myBuilder.AppendLine(@" ");
			myBuilder.AppendLine(" ");
			myBuilder.AppendLine(" ");

			myBuilder.AppendLine(" ");
			myBuilder.AppendLine("@page Section1 ");
			myBuilder.AppendLine("{");

			if (targetOrientation == PageOrientation.Portrait)
			{
				myBuilder.AppendLine("    size:8.5in 11.0in;");
			}
			else
			{
				myBuilder.AppendLine("    size:11.0in 8.5in;");
			}

			myBuilder.AppendLine("    mso-page-orientation:" + targetOrientation.ToString() + ";");

			switch (pageMargins)
			{
				case Test.Framework.Common.Core.WordHelper.PageMarginInInches._0_POINT_5_:
					myBuilder.AppendLine("    margin:0.5in 0.5in 0.5in 0.5in;");
					break;
				case Test.Framework.Common.Core.WordHelper.PageMarginInInches._1_POINT_0_:
					myBuilder.AppendLine("    margin:1.0in 1.0in 1.0in 1.0in;");
					break;
				case Test.Framework.Common.Core.WordHelper.PageMarginInInches._1_POINT_5_:
					myBuilder.AppendLine("    margin:1.5in 1.5in 1.5in 1.5in;");
					break;
				case Test.Framework.Common.Core.WordHelper.PageMarginInInches._2_POINT_0_:
					myBuilder.AppendLine("    margin:2.0in 2.0in 2.0in 2.0in;");
					break;
				default:
					myBuilder.AppendLine("    margin:1.0in 1.0in 1.0in 1.0in;");
					break;
			}

			myBuilder.AppendLine("} ");

			myBuilder.AppendLine("div.Section1 ");
			myBuilder.AppendLine("{ ");
			myBuilder.AppendLine("    page: Section1; ");
			myBuilder.AppendLine("} ");

			myBuilder.AppendLine(" ");
			myBuilder.AppendLine(" " );
			myBuilder.AppendLine(" " );
			myBuilder.AppendLine("<div class='Section1'> " );

			myPrefix = myBuilder.ToString();

			return myPrefix;
		}

		public static string GetHtmlBodyCleaned(string targetBody)
		{
			string myBodyCleaned = "";

			myBodyCleaned = (targetBody + "").Trim();

			myBodyCleaned.Replace(@"<br />", @"<br />");
			myBodyCleaned.Replace(@"<br />", @"<br />");
			myBodyCleaned.Replace(@"<p>", @"</p><p>");
			myBodyCleaned.Replace(@"</p>", @"");

			return myBodyCleaned;
		}

		public static string GetHtmlSuffix()
		{
			string mySuffix = "";

			StringBuilder myBuilder = new StringBuilder();
			myBuilder.AppendLine("</div> ");
			myBuilder.AppendLine(" " );
			myBuilder.AppendLine(" ");
			mySuffix = myBuilder.ToString();

			return mySuffix;
		}

		/// 
		/// This will set the client-script-block on the target page.
		/// 
		/// This is the page that contains the data to be exported.
		/// This is the name to use for the client script function.
		/// This is any string that idenfies this script block uniquely on the page.
		/// This is the ClientID of the DIV tag that holds the data that is being exported.
		/// This is the ID of the INPUT tag that holds the InnerHtml that is being exported.
		public static void SetClientScriptBlock(System.Web.UI.Page targetPage, string targetScriptFunctionName, string targetScriptKey, string targetDivTagClientId, string targetInputTagClientId)
		{
			//Validate the given Page.

			if (targetPage == null)
			{
				throw new System.ApplicationException("The given object, targetPage, is null.");
			}

			//Validate the given key for the script-block.

			targetScriptKey = (targetScriptKey + "").Trim();

			if (targetScriptKey.Length <= 0)
			{
				throw new System.ApplicationException("The value targetScriptKey.Length.ToString()='" + targetScriptKey.Length.ToString() + "' is not valid.");
			}

			//Validate the given function name.

			targetScriptFunctionName = (targetScriptFunctionName + "").Trim();

			if (targetScriptFunctionName.Length <= 0)
			{
				throw new System.ApplicationException("The value targetScriptFunctionName.Length.ToString()='" + targetScriptFunctionName.Length.ToString() + "' is not valid.");
			}

			//Validate the given ID for the DivTag.

			targetDivTagClientId = (targetDivTagClientId + "").Trim();

			if (targetDivTagClientId.Length <= 0)
			{
				throw new System.ApplicationException("The value targetDivTagClientId.Length.ToString()='" + targetDivTagClientId.Length.ToString() + "' is not valid.");
			}

			//Validate the given ID for the InputTag.

			targetInputTagClientId = (targetInputTagClientId + "").Trim();

			if (targetInputTagClientId.Length <= 0)
			{
				throw new System.ApplicationException("The value targetInputTagClientId.Length.ToString()='" + targetInputTagClientId.Length.ToString() + "' is not valid.");
			}

			Type myTypeToUse = targetPage.GetType();

			if (!targetPage.ClientScript.IsClientScriptBlockRegistered(myTypeToUse, targetScriptKey))
			{
				string myScriptCode = Test.Framework.Common.Core.WordHelper.GetClientScript(targetScriptFunctionName, targetDivTagClientId, targetInputTagClientId);
				const bool addScriptTagsFlag = false;
				targetPage.ClientScript.RegisterClientScriptBlock(myTypeToUse, targetScriptKey, myScriptCode, addScriptTagsFlag);
			}
		}

		/// 
		/// This will get the client-script-block that is required for the call.
		/// 
		/// This is the name to use for the client script function.
		/// This is the ID of the DIV tag that holds the data that is being exported.
		/// This is the ID of the INPUT tag that holds the InnerHtml that is being exported.
		/// This is the client script.
		public static string GetClientScript(string targetScriptFunctionName, string targetDivTagClientId, string targetInputTagClientId)
		{
			string myScript = "";

			//Validate the given function name.

			targetScriptFunctionName = (targetScriptFunctionName + "").Trim();

			if (targetScriptFunctionName.Length <= 0)
			{
				throw new System.ApplicationException("The value targetScriptFunctionName.Length.ToString()='" + targetScriptFunctionName.Length.ToString() + "' is not valid.");
			}

			//Validate the ID for the DivTag.

			targetDivTagClientId = (targetDivTagClientId + "").Trim();

			if (targetDivTagClientId.Length <= 0)
			{
				throw new System.ApplicationException("The value targetDivTagClientId.Length.ToString()='" + targetDivTagClientId.Length.ToString() + "' is not valid.");
			}

			//Validate the ID for the InputTag.

			targetInputTagClientId = (targetInputTagClientId + "").Trim();

			if (targetInputTagClientId.Length <= 0)
			{
				throw new System.ApplicationException("The value targetInputTagClientId.Length.ToString()='" + targetInputTagClientId.Length.ToString() + "' is not valid.");
			}

			//Get a worker object.
			StringBuilder myBuilder = new StringBuilder();

			//Build the text.

			myBuilder.AppendLine(" ");
			myBuilder.AppendLine("  ");
			myBuilder.AppendLine(" function " + targetScriptFunctionName + "() ");
			myBuilder.AppendLine(" { ");
			myBuilder.AppendLine("     //Get the element DIV that contains the GridView that contains the data. ");
			myBuilder.AppendLine("     var myElementSource = document.getElementById('" + targetDivTagClientId + "'); ");
			myBuilder.AppendLine("     //Get a handle to the element that is the hidden field that will hold the data for export. ");
			myBuilder.AppendLine("     var myElementDestination = document.getElementById('" + targetInputTagClientId + "'); ");
			myBuilder.AppendLine("     //Copy from the the source to the destination. ");
			myBuilder.AppendLine("     myElementDestination.value = myElementSource.innerHTML; ");
			myBuilder.AppendLine(" } ");
			myBuilder.AppendLine("  ");
			myBuilder.AppendLine(" ");

			//Get the text.
			myScript = myBuilder.ToString();

			return myScript;
		}

		public static void ExportToWord(
			System.Web.UI.Page targetPage, 
			string innerHtmlFromDiv, 
			string targetOrientation, 
			string targetMarginInInches, 
			Test.Framework.Common.Core.WordHelper.FileExtension targetExtension)
		{
			Test.Framework.Common.Core.WordHelper.PageOrientation myOrientation = Test.Framework.Common.Core.WordHelper.ConvertToPageOrientationByForce(targetOrientation);
			Test.Framework.Common.Core.WordHelper.PageMarginInInches myMarginInInches = Test.Framework.Common.Core.WordHelper.ConvertToPageMarginInInchesByForce(targetMarginInInches);

			//Call a helper.
			Test.Framework.Common.Core.WordHelper.ExportToWord(targetPage, innerHtmlFromDiv, myOrientation, myMarginInInches, targetExtension);
		}

		/// 
		/// This will export the given innerHtml to a single-worksheet, Word-friendly, HTML file.
		/// 
		/// This is the current page.
		/// This is the InnerHtml from a DIV that holds the data to be exported.
		/// This is the orientation for the output.
		/// This is the margin-size for the output.
		/// This is the extension for the output.
		public static void ExportToWord(
			System.Web.UI.Page targetPage, 
			string innerHtmlFromDiv, 
			Test.Framework.Common.Core.WordHelper.PageOrientation targetOrientation, 
			Test.Framework.Common.Core.WordHelper.PageMarginInInches targetMarginInInches, 
			Test.Framework.Common.Core.WordHelper.FileExtension targetExtension)
		{
			//NOTE: 20080925. This may work with other HTML passed to it (not just InnerHtml from a DIV) but so far it has only been tested with InnerHtml from a DIV.

			//Validate the given Page.
			if (targetPage == null)
			{
				throw new System.ApplicationException("The given object, targetPage, is null.");
			}

			//Validate the given Response.
			if (targetPage.Response == null)
			{
				throw new System.ApplicationException("The given object, targetPage.Response, is null.");
			}

			HttpResponse myTargetResponse = targetPage.Response;

			//Validate the given InnnerHtml.
			innerHtmlFromDiv = (innerHtmlFromDiv + "").Trim();

			if (innerHtmlFromDiv.Length  Test.Framework.Common.Core.WordHelper.InnerHtmlLengthMax)
			{
				throw new System.ApplicationException(
					"The given value innerHtmlFromDiv.Length.ToString()='" + innerHtmlFromDiv.Length.ToString() + 
					"' is not valid because it must be less-than-or-equal-to InnerHtmlLengthMax='" + Test.Framework.Common.Core.WordHelper.InnerHtmlLengthMax.ToString() + "'.");
			}

			//Get a working builder.
			StringBuilder myBuilder = new StringBuilder();

			//Call a helper to get the standard prefix that is written when Word 2003 saves from ".XLS" to ".HTM".

			string myHtmlPrefix = "";
			myHtmlPrefix = Test.Framework.Common.Core.WordHelper.GetHtmlPrefix(targetOrientation, targetMarginInInches);

			//Add the prefix.
			myBuilder.Append(myHtmlPrefix);

			//Get the basline HTML to be exported.
			string myHtmlBody = innerHtmlFromDiv;

			myHtmlBody = Test.Framework.Common.Core.WordHelper.GetHtmlBodyCleaned(myHtmlBody);

			//Add the body.
			myBuilder.Append(myHtmlBody);

			//Call a helper to get the standard suffix that is written when Word 2003 saves from ".XLS" to ".HTM".
			string myHtmlSuffix = Test.Framework.Common.Core.WordHelper.GetHtmlSuffix();

			//Add the suffix.
			myBuilder.Append(myHtmlSuffix);

			//Get a unique suffix for the output file.
			string DateTimeStringSuffix = DateTime.Now.ToString("yyyyMMddHHMMssfffffff");

			//Prepare the response.
			myTargetResponse.Clear();
			myTargetResponse.ClearHeaders();
			myTargetResponse.AddHeader("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0, post-check=0, pre-check=0");
			myTargetResponse.AddHeader("Content-transfer-encoding", "binary");
			myTargetResponse.AddHeader("Pragma", "anytextexeptno-cache, true");
			myTargetResponse.AddHeader("content-disposition", "attachment;filename=EXPORT_" + DateTimeStringSuffix + "." + targetExtension.ToString());
			string myHtmlComplete = myBuilder.ToString();

			//Prepare the page.
			targetPage.EnableViewState = false;

			//Write.
			myTargetResponse.Write(myHtmlComplete);

			//End the process, which must be done outside of all try-catch blocks.
			myTargetResponse.End();
		}

		#endregion //Helpers
	}
}

This is a sample usage code-infront…

<%@ page autoeventwireup="true" codefile="ViewerFormVersion02.aspx.cs" enableeventvalidation="false" inherits="Test.ExportForWord.Web.Components.Forms.Private.Administrator.ViewerFormVersion02" language="C#" maintainscrollpositiononpostback="true" validaterequest="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
	<title>ViewerForWord</title>
</head>
<body>
	<form id="form1" runat="server">
	<p>
		<asp:literal id="TopStatusLiteral" runat="server"></asp:literal>&nbsp;
	</p>
	<p>
		<asp:hyperlink id="MainHyperlink" runat="server" navigateurl="~/Default.aspx">Back</asp:hyperlink>
		<asp:label id="Label1" runat="server" font-bold="true">&nbsp;|&nbsp;</asp:label>
		<asp:linkbutton id="TopExportButton" runat="server" onclick="ExportButton_Click" text="Export"></asp:linkbutton>
	</p>
	<table border="1" cellpadding="5" cellspacing="0">
		<tr align="left" valign="top">
			<td align="left" valign="top">
				<asp:label id="Label5" runat="server">Export Settings</asp:label>
			</td>
		</tr>
		<tr align="left" valign="top">
			<td align="left" valign="top">
				<asp:label id="Label6" runat="server">Page Orientation</asp:label>
				<asp:radiobuttonlist id="OrientationRadioButtonList" runat="server" repeatcolumns="9" repeatdirection="horizontal" repeatlayout="table">
					<asp:listitem enabled="true" selected="true" text="Portrait" value="Portrait"></asp:listitem>
					<asp:listitem enabled="true" selected="false" text="Landscape" value="Landscape"></asp:listitem>
				</asp:radiobuttonlist>
			</td>
		</tr>
		<tr align="left" valign="top">
			<td align="left" valign="top">
				<asp:label id="Label7" runat="server">Page Margins</asp:label>
				<asp:radiobuttonlist id="MarginRadioButtonList" runat="server" repeatcolumns="9" repeatdirection="horizontal" repeatlayout="Table">
					<asp:listitem enabled="true" selected="true" text="0.5''" value="0.5"></asp:listitem>
					<asp:listitem enabled="true" selected="false" text="1.0''" value="1.0"></asp:listitem>
					<asp:listitem enabled="true" selected="false" text="1.5''" value="1.5"></asp:listitem>
					<asp:listitem enabled="true" selected="false" text="2.0''" value="2.0"></asp:listitem>
				</asp:radiobuttonlist>
			</td>
		</tr>
	</table>
	<p>
		<asp:label id="Label3" runat="server">Row&nbsp;Count:&nbsp;</asp:label><asp:label id="TotalRowCountLabel" runat="server">0</asp:label>
	</p>
	<div id="ExportDiv" runat="server">
		<asp:gridview id="WordGridView" runat="server" allowpaging="false" allowsorting="false" autogeneratecolumns="true" autogeneratedeletebutton="false" autogenerateeditbutton="false" autogenerateselectbutton="false" bordercolor="Silver" borderstyle="Solid" borderwidth="1px" emptydatatext="NULL" enablesortingandpagingcallbacks="false" enabletheming="false" enableviewstate="true" gridlines="both" showfooter="false" showheader="true">
			<headerstyle horizontalalign="left" verticalalign="Top" font-bold="true" />
			<rowstyle horizontalalign="left" verticalalign="Top" />
		</asp:gridview>
	</div>
	<input id="ExportInput" runat="server" type="hidden" value="" />
	<p>
		<asp:hyperlink id="Hyperlink1" runat="server" navigateurl="~/Default.aspx">Back</asp:hyperlink>
		<asp:label id="Label4" runat="server" font-bold="true">&nbsp;|&nbsp;</asp:label>
		<asp:linkbutton id="BottomExportButton" runat="server" onclick="ExportButton_Click" text="Export"></asp:linkbutton>
	</p>
	<p>
		<asp:literal id="BottomStatusLiteral" runat="server"></asp:literal><asp:label id="Label2" runat="server">&nbsp;</asp:label>
	</p>
	</form>
</body>
</html>

This is sample usage code-behind…

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace Test.ExportForWord.Web.Components.Forms.Private.Administrator
{
	/// 
	/// This will display data for Word export.
	/// 
	/// 
	/// Note that this page cannot be a cross-page-post-target because the source page will not display errors properly.
	/// 
	public partial class ViewerFormVersion02 : System.Web.UI.Page
	{
		#region MemberEnums

		/// 
		/// This is mock-data helper.
		/// 
		private enum ColumnName
		{
			Count,
			First,
			Middle,
			Last,
			Email,
		}

		#endregion //MemberEnums

		#region ValidationMethods

		/// 
		/// This is a mock custom validator.
		/// 
		private void ValidateExport()
		{
			//Continue.
		}

		#endregion //ValidationMethods

		#region HelperMethods

		/// 
		/// This is a mock-data helper.
		/// 
		/// This is mock data.
		private DataTable GetData()
		{
			DataTable myDataTable = new DataTable();
			myDataTable.Columns.Add(ColumnName.Count.ToString(), typeof(string));
			myDataTable.Columns.Add(ColumnName.First.ToString(), typeof(string));
			myDataTable.Columns.Add(ColumnName.Last.ToString(), typeof(string));
			myDataTable.Columns.Add(ColumnName.Email.ToString(), typeof(string));
			DataRow myDataRowTemp = null;

			for (int myCount = 1; myCount <= 9; ++myCount)
			{
				myDataRowTemp = myDataTable.NewRow();
				myDataRowTemp[ColumnName.Count.ToString()] = myCount.ToString();
				myDataRowTemp[ColumnName.First.ToString()] = Guid.NewGuid().ToString().Trim().ToUpper();
				myDataRowTemp[ColumnName.Last.ToString()] = Guid.NewGuid().ToString().Trim().ToUpper();
				myDataRowTemp[ColumnName.Email.ToString()] = Guid.NewGuid().ToString().Trim().ToUpper() + "@" + Guid.NewGuid().ToString().Trim().ToUpper() + ".COM";
				myDataTable.Rows.Add(myDataRowTemp);
			}

			myDataTable.AcceptChanges();

			return myDataTable;
		}

		#endregion //HelperMethods

		#region HandlerMethods

		protected void Page_Load(object sender, EventArgs e)
		{
			try
			{
				//Set values for export.
				const string ScriptPrefix = "_d26109b1_f78b_4c79_96a6_c87a892e4761_";
				const string ScriptSuffix = "GetHtmlForWord";
				Test.Framework.Common.Core.WordHelper.SetClientScriptBlock(this.Page, ScriptPrefix + ScriptSuffix, ScriptPrefix, this.ExportDiv.ClientID, this.ExportInput.ClientID);
				this.TopExportButton.OnClientClick = ScriptPrefix + ScriptSuffix + "();";
				this.BottomExportButton.OnClientClick = this.TopExportButton.OnClientClick;

				if (this.IsPostBack)
				{
					//Continue.
				}
				else
				{
					//To get data from Session, do something like this...
					//string myTestSessionData = this.Session[Test.ExportForWord.Common.Core.Enums.SessionKey.TestKeyName.ToString()].ToString();

					//To get data from this page, do something like this...
					DataTable myTableForWord = this.GetData();

					this.TotalRowCountLabel.Text = myTableForWord.Rows.Count.ToString();
					this.WordGridView.DataSource = myTableForWord;
					this.WordGridView.DataBind();
				}
			}
			catch (Exception ex)
			{

#if (DEBUG)
				this.TopStatusLiteral.Text = ex.ToString();
#else
				this.TopStatusLiteral.Text = ex.Message;
#endif

				this.BottomStatusLiteral.Text = this.TopStatusLiteral.Text;
			}
		}

		protected void ExportButton_Click(object sender, EventArgs e)
		{
			try
			{
				//This is optional code, shown in this code sample for demonstration purposed only.
				this.TopStatusLiteral.Text = "";
				this.BottomStatusLiteral.Text = this.TopStatusLiteral.Text;

				//This is optional code, shown in this code sample for demonstration purposed only.
				this.ValidateExport();
			}
			catch (Exception ex)
			{

#if (DEBUG)
				this.TopStatusLiteral.Text = ex.ToString();
#else
				this.TopStatusLiteral.Text = ex.Message;
#endif

				this.BottomStatusLiteral.Text = this.TopStatusLiteral.Text;
			}

			//Call a helper to do the work and do not wrap this call in a try-catch.
			Test.Framework.Common.Core.WordHelper.ExportToWord(
				this.Page,
				this.ExportInput.Value,
				this.OrientationRadioButtonList.SelectedValue,
				this.MarginRadioButtonList.SelectedValue,
				Test.Framework.Common.Core.WordHelper.FileExtension.DOC
				);
		}

		#endregion //HandlerMethods
	}
}

Advertisements

Author: mkamoski1

n/a