Delphi MS Word Ole自动化、ADO和外来字符

Delphi MS Word Ole自动化、ADO和外来字符,delphi,ms-word,ado,ole,widestring,Delphi,Ms Word,Ado,Ole,Widestring,我正在尝试将宽字符串文本从数据库(ADO/MS Access)导出到MS Word文档(Delphi 7),但未正确传输外来字符(即“è”而不是“č”): 我还尝试直接使用CreateOleObject(),但没有区别 我错过了什么 谢谢 你试过使用 WordApplication1.Selection.TypeText(ADOQuery1Text.AsWideString); 除此之外,我知道Delphi2009更好地处理Unicode(整个VCL现在直接支持它),这很可能会纠正您的问题

我正在尝试将宽字符串文本从数据库(ADO/MS Access)导出到MS Word文档(Delphi 7),但未正确传输外来字符(即“è”而不是“č”):

我还尝试直接使用
CreateOleObject()
,但没有区别

我错过了什么

谢谢

你试过使用

WordApplication1.Selection.TypeText(ADOQuery1Text.AsWideString); 

除此之外,我知道Delphi2009更好地处理Unicode(整个VCL现在直接支持它),这很可能会纠正您的问题

我认为这不是Word的问题,而是字符串在数据库中的存储方式的问题。它们可能保存为Ansi字符串,而不是Unicode/WideString字符串。如果这是真的,那么它们被保存在某种编码中,你必须知道如果你想正确地解码它们

下面是一个示例应用程序,演示如何将Ansi字符串转换为WideString并保存在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.
上面的代码使用来自的免费软件单元CodecUtilsWin32.pas


因此,我建议使用TStringField而不是TWideStringField,并将字符串转换为上面示例中的WideString。

No,Delphi7中没有AsWideString方法。在其他情况下,AsVariant可以正常工作。不幸的是,Delphi 7是客户的要求(这是他们唯一的版本)。尽管数据库中的字段标记为Unicode,但此解决方案可以工作。非常感谢,干得好!:)
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.