【问题标题】:Copy formated text from a cell in a Table in Word document to TRichEdit将 Word 文档表格中的单元格中的格式化文本复制到 RichEdit
【发布时间】:2012-08-27 01:50:31
【问题描述】:

我使用 OLE 自动化处理 Word 文档。 我可以使用

获取单元格的内容

Table.Cell(rowIndex, colIndex).Range.FormattedText

它返回 OleVariant。 我不确定我是否使用了正确的属性并且不知道如何在 TRichEdit 中粘贴此文本而不会丢失格式(例如上标文本)

【问题讨论】:

  • MS word 正在使用 RTF,并且 RTF 功能正在超时更改。 Delphi TRichedit 对 RTF 的支持有限,我认为它不支持 word 的表格。我不知道您需要什么样的格式化功能,但请记住 TRichedit 可能无法提供您需要的结果(即高级格式化可能会丢失或给出奇怪的结果)。另一种方法是使用 TRichedit 替换组件。
  • 哎呀...更正,上面的内容应该是...而且我认为它对单词表的支持有限。顺便说一句,我认为 Richedit 是 4.1 版。
  • 其实我不需要它来支持word的表格。我需要分别读取每个单元格,然后将其内容存储或保存为富文本,而不会丢失文本格式。没有预先格式化的单元格,只有下标、上标、粗体、斜体,仅此而已。效率不重要。

标签: delphi ms-word cell ole trichedit


【解决方案1】:

我设置了一个模型表单,上面只有一个 Richedit 和一个按钮。下面的代码可能不是实现这一目标的最佳方式,但它适用于 Win XP 上的 Word 2007。

uses  Word_TLB;

procedure TForm1.Button1Click(Sender: TObject);
var
  wordApp : _Application;
  doc : WordDocument;
  table : Word_TLB.Table;
  filename : OleVariant;
  aRange : Range;
  aWdUnits : OleVariant;
  count : OleVariant;
begin
  //need to back up 2 characters from range object to exclude table border.
  //Remove 1 character only if using selection
  count := -2;        
  aWdUnits := wdCharacter;
  filename := '"H:\Documents and Settings\HH\My Documents\testing.docx"';
  RichEdit1.Clear;
  try
    wordApp := CoWordApplication.Create;
    wordApp.visible := False;

    doc := wordApp.documents.open( filename, emptyparam,emptyparam,emptyparam,
      emptyparam,emptyparam,emptyparam,emptyparam,
      emptyparam,emptyparam,emptyparam,emptyparam,
      emptyparam,emptyparam,emptyparam,emptyparam );

    table := doc.tables.item(1);
    aRange := table.cell(3,1).Range;
    aRange.MoveEnd(aWdUnits, count); //This is needed so border is not included
    aRange.Copy;
    RichEdit1.PasteFromClipboard;
    RichEdit1.Lines.Add('');

  finally
    wordApp.quit(EmptyParam, EmptyParam, EmptyParam);
  end;
end;

结果如下: 。

唯一的问题是多行文本在 Richedit 中显示为单行。

【讨论】:

  • 正如您在自己的屏幕截图中看到的那样,您确实在最后切断了一个字符。因此,您必须将 count 设置为 -1 而不是 -2。此外,对于 Windows 7 上的 Word 2010,我必须在代码中更改以下内容:1)将 aRange 的类型从 Range 更改为 WordRange 和 2)在 aRange.MoveEndaRange.Copy 代码之间插入以下行:wordApp.Selection.Range.SetRange(aRange.Start, aRange.End_); 3) 或者,我将wordApp.documents.open 的第三个参数定义为OleVariant 变量readonly,我将其设置为true。这样可以防止在其他地方打开文档时出现问题
【解决方案2】:

我放弃了用 OLE 自动化解决这个问题。 TRichView 提供了所需的功能,但它不是免费的......

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多