最近遇到一个问题:
要求把html代码如(“<input value=value>”)以html格式粘贴到word中(即粘贴到word中后并不是文本,而是一个html文本框)
找了好久资料,终于解决.
首先请看html格式的数据在剪切版中的存放格式:
Version:0.9 // Version number of the clipboard. Starting version is 0.9.
StartHTML:71 // Byte count from the beginning of the clipboard to the start of the context, or -1 if no context
EndHTML:170 // Byte count from the beginning of the clipboard to the end of the context, or -1 if no context.
StartFragment:140 // Byte count from the beginning of the clipboard to the start of the fragment.
EndFragment:160 // Byte count from the beginning of the clipboard to the end of the fragment.
StartSelection:140 // Byte count from the beginning of the clipboard to the start of the selection.
EndSelection:160 // Byte count from the beginning of the clipboard to the end of the selection.
<!DOCTYPE>
<HTML>
<HEAD>
<TITLE>The HTML Clipboard</TITLE>
<BASE HREF="http://sample/specs">
</HEAD>
<BODY>
<!--StartFragment -->
<P>The Fragment</P>
<!--EndFragment -->
</BODY>
</HTML>
其中包含了换行符号.知道了html格式的数据在剪切版中的存储格式后,我们就可以解决这个问题了.首先我们要创建这样一段被格式化的字符串.下面的函数的功能是,接受要粘贴到word中的字符串参数如(“<input value=value>”)返回格式化后的html代码. htmlCode = getHtmlCode(fragmentcode)
Private Function getHtmlCode(ByVal htmlCode As String) As String
Dim htmlCodeLen As Integer = htmlCode.Length
‘其中113为要粘贴的html代码的起始字节位置+要粘贴的html代码的字节长度=要粘贴的html代码的结束位置
End Function
Dim htmlcodeformate As String = String.Format("{0:d12}", endfragment)
Dim clipboardStr As String = "Version:0.9" + vbCr + _
"StartHTML:50" + vbCr + _
"EndHTML:60" + vbCr + _
"StartFragment:000000000113" + vbCr + _
"EndFragment:" + htmlcodeformate + vbCr + _
"<!DOCTYPE>" + vbCr + _
"<HTML>" + vbCr + _
"<BODY>" + vbCr + _
htmlCode + vbCr + _
"</BODY>" + vbCr + _
"</HTML>" + vbCr
getHtmlCode = clipboardStr
下面使用这个方法获取格式化的html字符串,并复制到剪切板,然后粘贴到word中.
需要添加引用: Microsoft Word 11.0 Object Library组件
在应用程序的头部添加: Imports Microsoft.Office.Interop.Word
Dim datobj As New System.Windows.Forms.DataObject
Dim wordappl As New Microsoft.Office.Interop.Word.Application
Dim htmlCode As String
Dim fragmentcode As String = "<input name=test value=test>”
datobj.SetData(System.Windows.Forms.DataFormats.Html, htmlCode)
"把数据复制到剪切板
System.Windows.Forms.Clipboard.SetDataObject(datobj, True)
wordappl.Selection.PasteSpecial(DataType:=10)
但是如果数据中包含了中文,如一个表格的数据中有中文的部分就会出现乱码.需要首先把上面fragmentcode转换为utf-8的编码格式.
使用下面的方法:
Private Function encodingUTF8(ByVal code As String) As String
Dim encorderGB2312 As Encoding = Encoding.GetEncoding("gb2312")
Dim encorderUTF8 As Encoding = Encoding.UTF8
Dim codebytes As Byte() = encorderUTF8.GetBytes(code)
encodingUTF8 = encorderGB2312.GetString(codebytes)
End Function
这样这个问题就解决了.
我也学得不太好,有错误或问题请留言.