Cocoa Dev Cocoa Dev - 1 month ago 7
C# Question

RichTextBox loses all the formatting when exporting to word

I copied word content to richtextbox without loosing format perfectly, but now I am editing the content in the richtextbox.

Now I want to export the richtextbox content to a word document without losing any formating, in C# using WinForms. How do you do it?

WordApp.ActiveDocument.SaveAsQuickStyleSet("abc.doc");

Range rng = WordApp.ActiveDocument.Range(0, 0);


for (int i = 0; i < _dgvrow.Cells.Count; ++i)
{
// add code to loop thru controls and TypeText into word document

Label lb = (Label)this.Controls["lblfield" + (i+1).ToString()];
rng.Text += lb.Text;
rng.Select();

Control ctrl = this.Controls["txtfield" + (i+1).ToString()];

if(ctrl is RichTextBox)
{
RichTextBox rb = (RichTextBox)ctrl;
rng.Text += rb.Text + Environment.NewLine;
rng.Select();
}
else if (ctrl is TextBox)
{
TextBox rb = (TextBox)ctrl;
rng.Text += rb.Text + Environment.NewLine;
rng.Select();
}
}

Answer Source

The Text property just returns plain text. Use the Rtf property in order to return rtf-formatted text.

Unfortunately, Word does not have a method for inserting rtf text. However you can paste rtf-text from the clipboard

Clipboard.SetText(rb.Rtf, TextDataFormat.Rtf);
rng.Paste()