【问题标题】:VB.net, exporting RTF TextBox content to Excel CellVB.net,将 RTF 文本框内容导出到 Excel 单元格
【发布时间】:2019-08-26 08:02:19
【问题描述】:

我有一个 RichTextFormat 文本框,它包含多行、粗体、下划线和斜体文本。我需要将文本和字体样式都粘贴到 Excel 单元格中,因此“SAMPLE”仍将是“SAMPLE”而不是“SAMPLE”或“SAMPLE\b0 \par"。

我正在尝试

ExcelApp.Range("C2").Value = RTFTB.Rtf

这给了我

{\rtf1\ansi\ansicpg1252\deff0\deflang1036{\fonttbl{\f0\fnil\fcharset0 口径;}} \viewkind4\uc1\pard\b\f0\fs23 粗体样例\b0\par \par \i 斜体示例\i0\par \par \ul 下划线示例\par \par \ulnone SAMPLE NORMAL\par }

(RTF 代码)

ExcelApp.Range("C2").Value = RTFTB.Text

这给了我

粗体示例

斜体示例

下划线示例

正常样本

(没有字体样式)

【问题讨论】:

  • Excel 直接支持rtf...
  • 有没有办法保持粗体、下划线和斜体文本格式?
  • Google 的快速搜索表明,大多数解决方案都涉及将其复制粘贴到辅助程序 (Word) 中,然后将其粘贴到 Excel 中。 Word 会将格式转换为 Excel 可以读取的版本。
  • 我也看到了。我只是希望有比打开 Word Doc、粘贴、然后复制粘贴到 Excel 中更干净的东西/但谢谢!
  • 尽管我不愿意建议基于剪贴板的解决方案,并且在第一次复制到 MS Word 的类别中,您可以将 RTF 粘贴到已放置在 中的WebBrowser 控件中编辑模式 然后将其复制以将 HTML 放置在剪贴板上。 Excel 可以粘贴 HTML 剪贴板格式。

标签: excel vb.net interop rtf


【解决方案1】:

使用剪贴板传输信息并不是我喜欢提出的解决方案。但是,如果不将 RTF 转换为一系列 UI 自动化命令以模拟将文本添加到 Excel 并对其进行格式化,我就无法实现您的目标。

以下方法可用于将 RTF 作为 Html 放置在剪贴板上。它在可编辑模式下使用Webbrowser 控件将剪贴板的RTF 格式转换为Html。然后将 Html 放置在剪贴板上。

整体顺序是:

  1. 将 RTF 作为 RTF 放置在剪贴板上
  2. 创建一个 WebBrowser 控件并将其 DocumentText 设置为可编辑的 Html。

    在 WebBrowser.DocumentCompleted 事件处理程序中,

  3. 将 RTF 粘贴到 WebBrowser。

  4. 选择所有 Html 并复制。
  5. 最后,处理 WebBrowser 控件。

...

Public Shared Sub RtfToHtmlClipboard(rtf As String)
    Clipboard.SetData(DataFormats.Rtf, rtf)
    Dim browser As New WebBrowser
    AddHandler browser.DocumentCompleted, Sub(sender As Object, e As WebBrowserDocumentCompletedEventArgs)
                                            Dim wb As WebBrowser = CType(sender, WebBrowser)
                                            wb.Document.ExecCommand("Paste", False, Nothing)
                                            wb.Document.ExecCommand("SelectAll", False, Nothing)
                                            wb.Document.ExecCommand("Copy", False, Nothing)
                                            wb.Dispose()
                                          End Sub

    browser.DocumentText = "<html><body contenteditable=""true""></body></html>"
End Sub

编辑:

我使用上面的方法将 RTF 作为 HTML 放在剪贴板上,供用户手动粘贴。因此,我没有考虑使用对时间敏感的用例(例如 Excel 自动化)的含义。

对于自动化案例,最好不要每次都创建控件。此外,通过自动化(可能与 Office 剪贴板有关?)粘贴到 Excel 时,似乎还有其他机制在起作用,这再次证实了我不喜欢使用剪贴板。

但是,我发现以下作品可以将格式化的 RTF 复制到 Excel。我的 Office 版本是古老的(2007 年),所以希望这仍然适用于较新的版本。创建一个新的 WinForm 应用程序并将 Form1.VB 内容替换为以下内容以对其进行测试。运行代码时,单击“执行”按钮创建一个 Excel 实例并将一些格式化的 RTF 粘贴到其中。

Imports Excel = Microsoft.Office.Interop.Excel

Public Class Form1
    Private WithEvents rtb As RichTextBox
    Private WithEvents btnExecute As Button
    Private editableBrowser As WebBrowser

    Public Sub New()
        InitializeComponent()
        Setup()
    End Sub

    Private Sub Setup()
        editableBrowser = New WebBrowser With {
            .DocumentText = "<html><body contenteditable=""true""></body></html>"
        }

        btnExecute = New System.Windows.Forms.Button()
        rtb = New System.Windows.Forms.RichTextBox()
        SuspendLayout()

        btnExecute.Location = New System.Drawing.Point(580, 20)
        btnExecute.Size = New System.Drawing.Size(135, 50)
        btnExecute.TabIndex = 0
        btnExecute.Text = "Execute"
        btnExecute.UseVisualStyleBackColor = True
        AddHandler btnExecute.Click, AddressOf btnExecute_Click

        rtb.Location = New System.Drawing.Point(20, 20)
        rtb.Size = New System.Drawing.Size(450, 350)
        rtb.TabIndex = 1

        ClientSize = New System.Drawing.Size(800, 450)
        Controls.Add(Me.rtb)
        Controls.Add(Me.btnExecute)
        ResumeLayout()
    End Sub

    Private Sub btnExecute_Click(sender As Object, e As EventArgs)
        ExcelWork()
        COMCleanUp()
    End Sub

    Private Function GetRTF1() As String
        rtb.Clear()
        ' add some text and format it.
        Dim formattedText As String = "some sample rtf"
        rtb.Text = "This is " & formattedText & " to format and copy."
        rtb.CreateControl()
        rtb.SelectionStart = rtb.Find(formattedText)
        rtb.SelectionLength = formattedText.Length
        rtb.SelectionColor = Color.Red
        rtb.SelectionFont = New Font(Font.FontFamily, Font.Size + 2.0F, FontStyle.Bold)
        Return rtb.Rtf
    End Function

    Sub ExcelWork()
        Dim app As New Excel.Application
        Dim wb As Excel.Workbook = app.Workbooks.Add()
        Dim rng As Excel.Range = DirectCast(wb.Worksheets(1), Excel.Worksheet).Range("A1")

        PlaceRtfFAsHtmlOnClipboard(GetRTF1)
        ' for some reason rng.PasteSpecial just pastes as 
        ' unformatted text.  manual pasting results in formatted 
        ' text.
        ' The Worsheet.Paste method as well as the Worsheet.PasteSpecial
        ' methods will paste the Clipboard HTML format
        rng.Worksheet.PasteSpecial(Format:="HTML")
        'rng.Worksheet.Paste(rng)

        wb.Saved = True
        app.Visible = True  ' hand control over to user
        app.UserControl = True
    End Sub

    Private Sub PlaceRtfFAsHtmlOnClipboard(rtf As String)

        ' Clear the browser
        editableBrowser.Document.ExecCommand("SelectAll", False, Nothing)
        editableBrowser.Document.ExecCommand("Cut", False, Nothing)

        '  put rtf on clipboard
        Clipboard.SetData(DataFormats.Rtf, rtf)

        ' and paste to the editable broswer
        editableBrowser.Document.ExecCommand("Paste", False, Nothing)
        editableBrowser.Document.ExecCommand("SelectAll", False, Nothing)

        ' copy the html to the Clipboard
        editableBrowser.Document.ExecCommand("Copy", False, Nothing)
    End Sub

    Private Sub COMCleanUp()
        Do
            GC.Collect()
            GC.WaitForPendingFinalizers()
        Loop While System.Runtime.InteropServices.Marshal.AreComObjectsAvailableForCleanup
    End Sub

End Class 

【讨论】:

  • 这将是我正在寻找的内容,但我在尝试粘贴时收到 Pastespecial method of range class failed
  • 不幸的是它没有直接将 RTF 转换为 HTML
  • @Thryn,我发布了一些示例 Excel 自动化代码来演示将 RTF 粘贴到 Excel。试试看。
【解决方案2】:

我最终没有做 RTF 到 HTML 到 Excel 的解决方案,因为我没有这样做所需的技能

相反,我选择了这个:

  • 复制整个 RichTextBox

  • 将其粘贴到 Word 中

  • 复制 Word 文档

  • 将其粘贴到 Excel 中

它并不完美,因为它变成了图像而不是文本,但至少它有效。

这是我的代码:


'Phase 1 : Copy the RichTextBox

        TbRTF.SelectAll()
        TbRTF.Copy()
        Clipboard.SetData(DataFormats.Rtf, TbRTF.Rtf)

'Prepare phase 2 : Declare variables

        Dim aDoc As Word.Document = WordApp.Documents.Open("a blank word file.docx")
        Dim TheRange As Word.Range = aDoc.ActiveWindow.Selection.Range

'Phase 2 : Paste into Word

        WordApp.Visible = False

        TheRange.WholeStory()
        TheRange.Paste()

'Phase 3 : Copy from Word

        TheRange.WholeStory()
        WordApp.ActiveDocument.Select()
        WordApp.Selection.Copy()

'Phase 3.5 : Close Word

        aDoc.Close()
        WordApp.Quit()

'Phase 4 : Paste into Excel

        ExcelApp.Range("D" & r).PasteSpecial()

'Phase 4.5 : Close Excel

        Classeur.SaveAs("FinishedExcelFile.xlsx")
        Classeur.Close()
        ExcelApp.Quit()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 2022-12-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多