首页 文章

导出到word时,RichTextBox丢失所有格式

提问于
浏览
1

我将单词内容复制到richtextbox而没有完全失去格式,但现在我正在编辑richtextbox中的内容 .

现在,我想在使用WinForms的C#中将richtextbox内容导出到word文档而不会丢失任何格式 . 你怎么做呢?

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();
    }
}

3 回答

  • 0

    RichTextBoxText 属性只返回纯文本 . 使用 Rtf 属性返回rtf格式的文本 .

    不幸的是,Word没有插入RTF文本的方法 . 但是,您可以从剪贴板粘贴RTF文本

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

    你想获得控件的rich text format,而不仅仅是plain text .

    rb.Text 替换为 rb.Rtf .

    来自MSDN:

    Text属性不返回有关应用于RichTextBox内容的格式的任何信息 . 要获取富文本格式(RTF)代码,请使用Rtf属性 .

    另外,如果你想save the rich text format to a file,那就是内置的:

    rb.SaveFile(yourFilePath);
    
  • 2

    通过运行查看你的说法,我可以建议我正确编码 .

    使用保存文件方法将编码的富文本框保存为.rtf或.doc,然后在Microsoft Word中打开 .

    不会失败 .

    带着敬意 .

相关问题