Question

I have ListView on my form containing names and numbers and I have to provide printing MSWord document with those data filled into document's tables. Everything works fine with english characters but when I try to send some eastern European or Russian characters it is visible in document as "?" or some "trash". Also I can't read those characters from document back to application.

My questions are:

  1. How to send characters like "ЉЊĐŠŽČ" to Word document?
  2. How to read these characters from MSWord back to application?

In short, code looks like this:

word := CreateOleObject('Word.Application');
word.Visible := true;
doc := word.documents.Open(ExtractFilePath(Application.ExeName) + '\tpl.doc');

table := word.ActiveDocument.Tables.Item(1);
table.Cell(1,2).Range.Text := 'MY TEXT';

word.ActiveDocument.Close;
word.Quit;
word := UnAssigned;
doc := UnAssigned;
table := UnAssigned;

I can change font's name, size and color properties but can't do that with charset property.

Anybody?


Software installed:

  • Windows XP Professional
  • Microsoft Word 2003
  • Delphi 7 Enterprise Edition
Was it helpful?

Solution

The issue comes from the fact that you're calling Word via OLE Automation using late binding.

So Range.Text is not known as a method expecting a WideString (Unicode) content, but plain ASCII text, under Delphi 7.

First solution could be to use Delphi 2009 and later. The new string type made such Unicode assignment transparent.

Under Delphi 7, what about forcing the type cast to WideString:

 table.Cell(1,2).Range.Text := WideString('MY TEXT'); 

or using a temporary variable, like this:

 var tmp: WideString; 

   tmp := 'ЉЊĐŠŽČ'
   table.Cell(1,2).Range.Text := tmp; 

Another possibility could be to use not late-binding, but direct declaration of the OLE interface of Office, importing the "Microsoft Word ??? Object library" from the "Project" menu of the IDE.

You'll have widestring types in the imported interfaces, e.g:

Range = interface(IDispatch)
  ['{0002095E-0000-0000-C000-000000000046}']
  function Get_Text: WideString; safecall;
  procedure Set_Text(const prop: WideString); safecall;
  (...)
  property Text: WideString read Get_Text write Set_Text;

So you won't have any issue with Ansi charset any more.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top