views:

594

answers:

2

I'm trying to export WideString texts from the database (ADO / MS Access) to the MS Word document (Delphi 7), but foreign characters are not correctly transferred (i.e. "è" instead of "č"):

while not ADOQuery1.Eof do
begin
  WordApplication1.Selection.TypeText(ADOQuery1Text.AsVariant); // TWideStringField
  WordApplication1.Selection.TypeParagraph;
  ADOQuery1.Next;
end;

I've also tried to use CreateOleObject() directly, but no difference.

What am I missing?

Thanks!

A: 

Have you tried using

WordApplication1.Selection.TypeText(ADOQuery1Text.AsWideString);

Short of that, I know that Delphi 2009 has better handling of Unicode (entire VCL now supports it directly) that would most likely correct your problem.

skamradt
No, there's no AsWideString method in Delphi 7. In other cases AsVariant works okay.
vrad
And unfortunately, Delphi 7 is client's requirement (it's the only version they have).
vrad
+3  A: 

I think it's not a problem with Word but rather with the way the strings are stored in the database. They are probably saved as Ansi strings, not as Unicode/WideString strings. And if that is true, then they are saved in some encoding which you must know if you want them to be decoded correctly.

Here is a sample application demonstrating how to convert Ansi string into WideString and save it in Word:

program Project1;
{$APPTYPE CONSOLE}
uses
  SysUtils,
  ComObj,
  ActiveX,
  CodecUtilsWin32;

procedure Test();
var
  wordApp, wordDoc: Variant;
  ansiStr: string;
  codec: TUnicodeCodec;

  function str2WideStr(const s: string): WideString;
  var
    i: Integer;
  begin
    codec.DecodeStr(@s[1], Length(s), Result);
  end;

begin
  codec := TEncodingRepository.CreateCodecByAlias('ISO-8859-2');

  ansiStr := #$BF#$F3#$B3#$E6; //"zólc"

  wordApp := CreateOleObject('Word.Application'); 
  wordDoc := wordApp.Documents.Add;
  wordApp.Selection.TypeText(str2WideStr(ansiStr));
  wordDoc.SaveAs('C:\sample.doc');
  wordDoc.Close();
  wordApp.Quit(False);
end;

begin
  CoInitialize(nil);
  Test();
end.

The code above uses freeware unit CodecUtilsWin32.pas from Utility Library v.2.0.18

So I'd suggest using TStringField instead of TWideStringField and converting the strings to WideStrings as in the above example.

tomazy
Although fields in the database are marked as Unicode, this solution works. Thank you very much and well done! :)
vrad