开发者

Word Automation Multiple Paste Problem

Is there a better way to paste HTML fragments into a Word document than via the clipboard from C#?

using Word = Microsoft.Office.Interop.Word;

I'm using some code that puts HTML into the clipboard:

HtmlFragment.CopyToClipboard(changedText);

I have a selection in word (from a formfield) and I do:

 word.Selection.Paste();

But sometimes it just t开发者_Python百科hrows a COM exception. If I add

  Thread.Sleep(100);

I can get it to work, but that's not ideal.

The Insert methods look like a better option but there is no Insert from HTML.

So what's the best way to insert lots of HTML fragments into Word quickly using the automation interfaces?

Edit

Some good advice in the responses but the issue turned out to be a simple <br> tag causing word to fail on paste.


For interop, instead of Selection.Paste you'll want to use Selection.PasteSpecial with a WdPasteDataType of wdPasteHTML.

If you're using the new formats of Word (i.e. 2007/2010), you could give up interop all together and just go with WordprocessingML (using the Open XML SDK or just free-hand it with Linq and System.IO.Packaging). Or you could just it in conjunction with Interop if that was a need.

If you're using Open XML, you could just use altChunk to import HTML. Here's an example (which includes an example for HTML) at How to Use altChunk for Document Assembly. And another (fresh off the presses - it was released today): Importing HTML that contains Numbering using altChunk.


+1 to Otaku's comments, though, generally speaking, i've found it best to use the various RANGE.* functions for pasting in data than the Selection object, or pasting through the clipboard. the main reason is, if you paste through the clipboard, you scramble whatever was on the clipboard (which might not be what the user wants to happen).

the Selection object applies across all open word documents, which can get you in trouble in some cases. Unfortunately there are a few things that you just about can't do any other way.

And, there are some things (Like altering text at the current cursor position) that you MUST use the selection object for.


+1 to DarinH comments. Also something to note is that you can paste on any place in the document using Range without having to change the selection of the document (the cursor in the document).

Sometimes PasteAndFormat throws an Exception on freshly created Documents, check my reply here if that happens: https://stackoverflow.com/a/65796482/15001063

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜