How to read/write local characters from/to MSWord 2003 using Delphi 7?
I have ListView on my form containing names and numbers and I have to provide printing MSWord document with those data filled int开发者_JS百科o 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:
- How to send characters like
"ЉЊĐŠŽČ"
to Word document? - 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
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.
精彩评论