Free Support Forum - aspose.com

Exporting data to word file

Thanks for ur support. I have attached a file. I have to make that file that opens in Word on button click. It was developed using Xml but now I want it without Xml with same format. Can u Please tell me how can I do this??


This message was posted using Page2Forum (attachment) from Aspose.Words for .NET - Documentation

Hi

Thanks for your request. As I can see your document is a template with placeholders. If you would like to fill the template with data, I think Mail Merge would be the best option. Please follow the link for more information:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/simple-mail-merge-explained.html

in this case, you should replace your placeholders with merge fields. You can do this manually in MS Word or programmatically using Aspose.Words. The below code demonstrates how you can replace placeholders with merge fields:

[Test]

public void Test001()

{

Document doc = new Document(@"Test001\in.doc");

doc.Range.Replace(new Regex(@"##(?.*?)##}"), new ReplaceEvaluatorFindAndInsertMergefield(), false);

doc.Save(@"Test001\out.doc");

}

private class ReplaceEvaluatorFindAndInsertMergefield : IReplacingCallback

{

///

/// This method is called by the Aspose.Words find and replace engine for each match.

/// This method highlights the match string, even if it spans multiple runs.

///

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)

{

// This is a Run node that contains either the beginning or the complete match.

Node currentNode = e.MatchNode;

// The first (and may be the only) run can contain text before the match,

// in this case it is necessary to split the run.

if (e.MatchOffset > 0)

currentNode = SplitRun((Run)currentNode, e.MatchOffset);

// This array is used to store all nodes of the match for further removing.

ArrayList runs = new ArrayList();

// Find all runs that contain parts of the match string.

int remainingLength = e.Match.Value.Length;

while (

(remainingLength > 0) &&

(currentNode != null) &&

(currentNode.GetText().Length <= remainingLength))

{

runs.Add(currentNode);

remainingLength = remainingLength - currentNode.GetText().Length;

// Select the next Run node.

// Have to loop because there could be other nodes such as BookmarkStart etc.

do

{

currentNode = currentNode.NextSibling;

}

while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));

}

// Split the last run that contains the match if there is any text left.

if ((currentNode != null) && (remainingLength > 0))

{

SplitRun((Run)currentNode, remainingLength);

runs.Add(currentNode);

}

// Create Document Buidler aond insert MergeField

DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document as Document);

builder.MoveTo((Run)runs[runs.Count - 1]);

string fieldName = e.Match.Groups["FieldName"].Value;

builder.InsertField(string.Format("MERGEFIELD {0}", fieldName), string.Format("«{0}»", fieldName));

// Now remove all runs in the sequence.

foreach (Run run in runs)

run.Remove();

// Signal to the replace engine to do nothing because we have already done all what we wanted.

return ReplaceAction.Skip;

}

///

/// Splits text of the specified run into two runs.

/// Inserts the new run just after the specified run.

///

private static Run SplitRun(Run run, int position)

{

Run afterRun = (Run)run.Clone(true);

afterRun.Text = run.Text.Substring(position);

run.Text = run.Text.Substring(0, position);

run.ParentNode.InsertAfter(afterRun, run);

return afterRun;

}

}

Hope this helps.

Best regards,

Thanks for the help.But I am not getting how can I replace data in it from Database

Hi Monika,

Thanks for your inquiry. In case of using mail merge, you simply need to get data from your database as DataTable or IDataReader and execute mail merge as described here:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/howto-execute-simple-mail-merge.html

Best regards,

I am really not getting from this link. I want data from a very large database i.e from backend.

Can u simply tell me how could I replace data from my database to the aove template

Hi Monika,

Thanks for your request. but it is not quite clear for me what you cannot achieve. The algorithm is pretty clear:

1. Get data from your data base;

2. Open template;

3. Execute mailmerge;

4. Save output.

You can also take a look at the demos, Maybe they will help you. For example:

http://www.aspose.com/demos/.net-components/aspose.words/csharp/general/dinner-invitation.aspx

Best regards,

I have attached the file. In this template there are fieldnames. Now I want to replace these fieldnames with the values from the database. I have tried a lot of options,but didn’t work. I also not able to understand mailmerge from the links. Can u send me some code to do this. Also Mailmerge.Execute(datatable) display empty word document. Or whether can I made this word file at runtime

Hi Monika,

Thanks for your request. Here is the code example you asked about:

[Test]

public void Test001()

{

// Create a dummy datasource. In yor case you are gettign data from database.

DataTable data = new DataTable();

data.Columns.Add("EOBLogo");

data.Columns.Add("BusinessName");

data.Columns.Add("Address1");

data.Columns.Add("CityStateZip");

data.Columns.Add("ClientPhoneNo");

data.Columns.Add("ClientFax");

data.Columns.Add("BillReviewID");

data.Columns.Add("BillDate");

data.Columns.Add("Provider");

data.Columns.Add("ProAddress");

data.Columns.Add("ProCity");

data.Columns.Add("ProState");

data.Columns.Add("ProZip");

data.Columns.Add("ProviderTIN");

data.Columns.Add("PayName");

data.Columns.Add("PayAdd1");

data.Columns.Add("PayState");

data.Columns.Add("PaZIP");

data.Columns.Add("PayType");

data.Columns.Add("PayCity");

data.Columns.Add("Reconsideration");

data.Columns.Add("ClaimNumber");

data.Columns.Add("DOI");

data.Columns.Add("SSN");

data.Columns.Add("DOB");

data.Columns.Add("ProviderInvoice");

data.Columns.Add("ReimbursementDisclaimer");

data.Columns.Add("Claimant");

data.Columns.Add("DiagLineItem");

data.Columns.Add("TotalAmtText");

data.Columns.Add("TotalRPAmount");

data.Columns.Add("table");

data.Columns.Add("TotalAmount");

data.Columns.Add("PhysicianRText");

data.Columns.Add("ResoncodeLSummery");

data.Columns.Add("RepricingDisclaimer");

// Fill datasource with some dummy data.

for (int i = 0; i < 2; i++)

{

data.Rows.Add(new object[]{ "EOBLogo", "BusinessName", "Address1", "CityStateZip", "ClientPhoneNo", "ClientFax",

"BillReviewID", "BillDate", "Provider", "ProAddress", "ProCity", "ProState", "ProZip"

, "ProviderTIN", "PayName", "PayAdd1", "PayCity", "PayState", "PaZIP", "PayType",

"Reconsideration", "ClaimNumber", "DOI", "SSN", "DOB", "ProviderInvoice",

"ReimbursementDisclaimer", "Claimant", "DiagLineItem", "TotalAmtText","TotalRPAmount",

"table", "TotalAmount", "PhysicianRText", "ResoncodeLSummery", "RepricingDisclaimer" });

}

// open template.

Document doc = new Document(@"Test001\EOBProviderCMS1500New.xml");

// Since in your document placeholders are used, before using MailMerge,

// you have to replace placeholders with mergefields.

doc.Range.Replace(new Regex(@"##(?.*?)##"), new ReplaceEvaluatorFindAndInsertMergefield(), false);

// Execute mail merge.

doc.MailMerge.Execute(data);

// Save output.

doc.Save(@"Test001\out.doc");

}

private class ReplaceEvaluatorFindAndInsertMergefield : IReplacingCallback

{

///

/// This method is called by the Aspose.Words find and replace engine for each match.

/// This method highlights the match string, even if it spans multiple runs.

///

ReplaceAction IReplacingCallback.Replacing(ReplacingArgs e)

{

// This is a Run node that contains either the beginning or the complete match.

Node currentNode = e.MatchNode;

// The first (and may be the only) run can contain text before the match,

// in this case it is necessary to split the run.

if (e.MatchOffset > 0)

currentNode = SplitRun((Run)currentNode, e.MatchOffset);

// This array is used to store all nodes of the match for further removing.

ArrayList runs = new ArrayList();

// Find all runs that contain parts of the match string.

int remainingLength = e.Match.Value.Length;

while (

(remainingLength > 0) &&

(currentNode != null) &&

(currentNode.GetText().Length <= remainingLength))

{

runs.Add(currentNode);

remainingLength = remainingLength - currentNode.GetText().Length;

// Select the next Run node.

// Have to loop because there could be other nodes such as BookmarkStart etc.

do

{

currentNode = currentNode.NextSibling;

}

while ((currentNode != null) && (currentNode.NodeType != NodeType.Run));

}

// Split the last run that contains the match if there is any text left.

if ((currentNode != null) && (remainingLength > 0))

{

SplitRun((Run)currentNode, remainingLength);

runs.Add(currentNode);

}

// Create Document Buidler aond insert MergeField

DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document as Document);

builder.MoveTo((Run)runs[runs.Count - 1]);

string fieldName = e.Match.Groups["FieldName"].Value;

builder.InsertField(string.Format("MERGEFIELD {0}", fieldName),string.Format("«{0}»", fieldName));

// Now remove all runs in the sequence.

foreach (Run run in runs)

run.Remove();

// Signal to the replace engine to do nothing because we have already done all what we wanted.

return ReplaceAction.Skip;

}

///

/// Splits text of the specified run into two runs.

/// Inserts the new run just after the specified run.

///

private static Run SplitRun(Run run, int position)

{

Run afterRun = (Run)run.Clone(true);

afterRun.Text = run.Text.Substring(position);

run.Text = run.Text.Substring(0, position);

run.ParentNode.InsertAfter(afterRun, run);

return afterRun;

}

}

Hope this helps.

Best regards,

Thank u so much. It really works.How can I make the binary format of this file??

Hi Monika,

Thanks for your request. You can save the output document in any format supported by Aspose.Words. In my example, I saved the output in binary DOC format. Please see the documentation for more information:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/save-a-document.html

Best regards,

can u exactly tell me in this link which method is to save it in binary format. That is not explained in it

Hi Monika,

Thanks for your request. The following code saved document in binary DOC format:

// Save output.

doc.Save("out.doc");

Save format is determined by the extension in this case.

Best regards,

Thanks. Actually I didn't know that it saves the file in Binary format with simply Save method

object[] add_data = new object[37];

add_data[1] = eob.Tables[0].Rows[0]["clientBusinessName"].ToString().Trim();

if (eob.Tables[0].Rows[0]["clientEOBPrintonEOBAddress2"].ToString().Trim() != "")

{

add_data[2] = eob.Tables[0].Rows[0]["clientEOBPrintonEOBAddress1"].ToString().Trim() + eob.Tables[0].Rows[0]["clientEOBPrintonEOBAddress2"].ToString().Trim();

}

else

{

add_data[2] = eob.Tables[0].Rows[0]["clientEOBPrintonEOBAddress1"].ToString().Trim();

//str = str.Replace("##Address1##", "");

}

add_data[3] = eob.Tables[0].Rows[0]["clientEOBPrintonEOBCity"].ToString().Trim() + ", " + eob.Tables[0].Rows[0]["clientEOBPrintonEOBState"].ToString().Trim() + " " + eob.Tables[0].Rows[0]["clientEOBPrintonEOBZip"].ToString().Trim();

I have done this for replacing values of the above template. Now I have a gridview in which data from datasource is bind. I want to pass this gridview object to add_data object. Can u tell me how could I do this.

Hi Monika,

Thanks for your inquiry. Actually, the question is not related to Aspose.Words. However, you can try using solution described here to extract data from GridView as DataTable:

http://www.codeproject.com/KB/aspnet/GridView_To_DataTable.aspx

Hope this helps.

Best regards,

I am having the following code:

docbld.InsertCell();

docbld.Write(string.Format("{0:c}", (LineItem.Tables[1].Rows[0]["TotalCharges"].ToString().Trim())));

docbld.InsertCell();

docbld.Write(string.Format("{0:c}", (LineItem.Tables[1].Rows[0]["TotalOMFSReduction"].ToString().Trim())));

docbld.InsertCell();

docbld.Write(string.Format("{0:c}", (LineItem.Tables[1].Rows[0]["TotalPPOReduction"].ToString().Trim())));

docbld.InsertCell();

docbld.Write(string.Format("{0:c}", (LineItem.Tables[1].Rows[0]["TotalRecommendedPayment"].ToString().Trim())));

now I want to add this code to the object

object[] add_data = new object[37];

Can I add documentbuilder to the object

add_data[1] = ??

Hi Monika,

Thanks for your request. But it is not quite clear for me why you need this? Could you please clarify?

Best regards,

I am having the template attached with this message. In this I have replaced the data. Now I also have to run time table in it.I developed it using DocumentBuilder.Now I want to replace this table with the text #table of the template. I want to do it using object. But I don't know how to pass this table to the object.

object is:

object[] add_data = new object[37];

Hi Monika,

Thank you for additional information. If you are filling the document using Mail Merge approach, you can use IFieldMergingCallback to achieve what you need. Please see the documentation for more details:

http://www.aspose.com/documentation/.net-components/aspose.words-for-.net/aspose.words.reporting.ifieldmergingcallback.html

Best regards,