想用一个线程写excel表格,在线程中调用了createOleObject函数老是出错(100分)

  • 主题发起人 主题发起人 fatih
  • 开始时间 开始时间
F

fatih

Unregistered / Unconfirmed
GUEST, unregistred user!
是不是不能在线程中写调用呀!该怎么做呀 拜托了
unit UnitWriteTbThread;
interface
uses
// Classes,Grids,SysUtils,UnitProgress,Forms,ActnList,Wordxp,Windows;
Windows, Messages, Grids,SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,Comobj,ComCtrls,unitProgress,Excel2000,UnitFunc;
type
TWriteTbThread = class(TThread)
private
{ Private declarations }

protected
procedure Execute;
override;
procedure WriteExcel(aStringGrid:TStringGrid);
public
theStringGrid:TStringGrid;
fileName:WideString;
Style:Integer;
constructor Create(CreateSuspended:Boolean;aStringGrid:TStringGrid;workStyle:Integer);

end;

implementation
{ Important: Methods and properties of objects in visual components can only be
used in a method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure TWriteTbThread.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ TWriteTbThread }
constructor TWriteTbThread.Create(CreateSuspended:Boolean;aStringGrid:TStringGrid;workStyle:Integer);
begin

FreeOnTerminate:=True;
Style:=workStyle;
theStringGrid:=aStringGrid;
fileName:='d:/test.xls';
if (fileName='') then
begin
MessageDlg('文件名不正确!',mtInformation,[mbok],0);
exit;
end;
inherited Create(CreateSuspended);
end;
procedure TWriteTbThread.Execute;
var
colSum,rowSum:Integer;
begin
{ Place thread code here }
colSum:=theStringGrid.ColCount;
rowSum:=theStringGrid.RowCount;
if (Style=0) then
begin
writeTb(colSum,rowSum);
end
else
if (Style=1) then
begin
WriteExcel(theStringGrid);
end;
end;

procedure TWriteTbThread.WriteExcel(aStringGrid:TStringGrid);
var
i,j:Integer;
rate:Int64;
ExcelApplication: Variant;
ExcelWorkBook: Variant;
begin

rate:=round(aStringGrid.RowCount/100);
try
ExcelApplication := CreateOleObject('Excel.Application');
ExcelWorkBook:=CreateOleObject('Excel.Sheet');
except
ShowMessage('您的机器上没有安装Excel。');
exit;
end;
ExcelWorkBook := ExcelApplication.Workbooks.Add;
for i:=1 to aStringGrid.RowCountdo
for j:=1 to aStringGrid.ColCountdo
ExcelWorkBook.Worksheets[1].Cells.item[i,j].value:=aStringGrid.Cells[j,i];
end;
end.
 
第一,你要知道到底发生了什么错误,这样有助于调试,用如下代码
try
on e:Exceptiondo
begin
ShowMessage('Error:'+e.Message);
end;
end;
第二,可能是需要在单元里增加
initialization
CoInitializeEx(nil,COINIT_MULTITHREADED);
finalization
CoUninitialize;
 
啊,上述两个函数在ActiveX单元中
 
你说什么在ActiveX中?
 
大哥呀急救呀。
老是说'尚未调用 CoInitialize' 到底该怎么调用呀 有样例吗?
我在delphi根本就找不到CoInitialize呀
 
CoInitializeEx,和CoUninitialize在AcitveX中,加上
initialization
CoInitializeEx(nil,COINIT_MULTITHREADED);
finalization
CoUninitialize;
肯定没问题.
 
你有没有调试上哪里出错了?
 
多人接受答案了。
 
我还没有试,看你们这么热心,就先把分给你们了。出了问题再问你们:)
 
CoInitializeEx在哪个单元里呀
 
后退
顶部