How to Insert Raw RTF into Excel

This is a question I have had a few times in the past with respect to Word, Excel and PowerPoint. I will focus on Excel for this example, but the basics apply just the same for any other application.

From time to time certain applications may generate reports or data in RTF or you may have a need to store RAW RTF into a database text field. There are a lot of advantages to RTF in this respect since it is a fully formatted document format, but it can be hard to get into an Office application without it looking… RAW. Disappointed smile

This is where this little snippet of code comes in handy: Hot smile

Excel.Application LobjXL = Globals.ThisAddIn.Application;
// get the current data on the clipboard
IDataObject LobjClipboardContents = Clipboard.GetDataObject();
// extract the text/rtf
string LstrText = "" // <-- PUT YOUR RTF SOURCE HERE
// create an RTF control on the fly and use it
RichTextBox LobjRtfControl = new RichTextBox();
LobjRtfControl.Rtf = LstrText;
LobjRtfControl.SelectAll();
LobjRtfControl.Copy(); // copy the layout to the clipboard as RTF
// and paste
Excel.Worksheet LobjSheet = LobjXL.ActiveSheet;
LobjSheet.Paste();
// then reset the clipboard to the original format
Clipboard.SetDataObject(LobjClipboardContents);

Leave a Reply