1 / 1 / 0
Регистрация: 30.06.2018
Сообщений: 9
1
RAD XE3+

Ошибка в работе потока. Excel Delphi 2010 Поток

20.06.2019, 22:20. Показов 1332. Ответов 8

Author24 — интернет-сервис помощи студентам
Доброго времени суток! В общем проблема такая: разрабатываю приложение на Delphi 10.1 c использованием библиотек Майдак и ТМС. Пытаюсь сделать экспорт данных из приложения (TADV_stringgrid) в создаваемый Excel файл в потоке... Бывают 3 ситуации 1)Поток отрабатывает нормально 2) Вылазит ошибка не хватает системных ресурсов 3) Не верный дескриптор
Подскажите где я мог ошибиться. П.С. До этого не работал с потоками, так что прошу не судите строго. Код прилагаю...


Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
unit Otcet;
 
interface
 
uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, AdvUtil, Vcl.ComCtrls, Vcl.Grids,
  AdvObj, BaseGrid, AdvGrid, Vcl.ExtCtrls, Vcl.StdCtrls, AdvCombo,
  AdvDateTimePicker, Vcl.Buttons, inifiles, Data.DB, DBAccess, MyAccess, MemDS, DateUtils, Math, ActiveX, ComObj, Excel2000,
  AdvProgressBar;
 
type
  TMyControl = class(TControl)
  public
    property Font;
end;
 
  TMyThread = class(TThread)
    private
      function FiltrStr(var S:string):string;
      procedure Excel_v;
    { Private declarations }
  protected
    procedure Execute; override;
end;
 
type
  TForm_Ot = class(TForm)
    Panel_ot1: TPanel;
    ASG_Ot: TAdvStringGrid;
    StatusBar1: TStatusBar;
    AdvDTP_ot_data1: TAdvDateTimePicker;
    AdvCB_ot_org: TAdvComboBox;
    AdvDTP_ot_data2: TAdvDateTimePicker;
    Bt_tab: TButton;
    Bt_sf_ot: TButton;
    E_poisk_ot: TEdit;
    Bt_clear_ot: TButton;
    Timer1: TTimer;
    MyQuery_ot_spr: TMyQuery;
    MyDataSource_ot: TMyDataSource;
    MyQuery_ot_buf: TMyQuery;
    MyQuery_ot_ok: TMyQuery;
    MyQuery_ot_ywt: TMyQuery;
    Bt_exel: TBitBtn;
    AdvPB_excel: TAdvProgressBar;
    procedure FormShow(Sender: TObject);
    procedure Bt_tabClick(Sender: TObject);
    procedure FormClose(Sender: TObject; var Action: TCloseAction);
    procedure Timer1Timer(Sender: TObject);
    procedure FormCreate(Sender: TObject);
    procedure Bt_sf_otClick(Sender: TObject);
    procedure Bt_clear_otClick(Sender: TObject);
    procedure E_poisk_otKeyUp(Sender: TObject; var Key: Word;
      Shift: TShiftState);
    procedure E_poisk_otExit(Sender: TObject);
    procedure E_poisk_otClick(Sender: TObject);
    procedure FormActivate(Sender: TObject);
    procedure Bt_exelClick(Sender: TObject);
  private
  function ObnovASG_Ot():boolean;
    { Private declarations }
  public
    { Public declarations }
  end;
 
var
  Form_Ot: TForm_Ot;
  MyThread: TMyThread;
 
implementation
 
{$R *.dfm}
 
uses Dm, Ohr, OK;
 
 
procedure TMyThread.Execute;
begin
   MyThread.Excel_v;
   {MyThread.Terminate;
   MyThread.Free;  }
end;
 
procedure TForm_Ot.Bt_clear_otClick(Sender: TObject);
begin
  ASG_Ot.ClearAll;
  Bt_sf_ot.Visible:=true;
  Bt_clear_ot.Visible:=false;
  AdvCB_ot_org.Enabled:=true;
  AdvDTP_ot_data1.Enabled:=true;
  AdvDTP_ot_data2.Enabled:=true;
end;
 
procedure TForm_Ot.Bt_exelClick(Sender: TObject);
var newPotokExcel:TMyThread;
begin
 if ASG_Ot.Cells[1,1]<>'' then begin
   newPotokExcel:=TMyThread.Create(true);
   newPotokExcel.FreeOnTerminate:=true;
   newPotokExcel.Priority:=tpIdle;
   newPotokExcel.Resume;
 end;
end;
 
procedure TForm_Ot.Bt_sf_otClick(Sender: TObject);
begin
  if AdvDTP_ot_data2.DateTime>AdvDTP_ot_data1.DateTime then begin
    ObnovASG_Ot;
    Bt_sf_ot.Visible:=false;
    Bt_clear_ot.Visible:=true;
    AdvCB_ot_org.Enabled:=false;
    AdvDTP_ot_data1.Enabled:=false;
    AdvDTP_ot_data2.Enabled:=false;
  end
  else begin
    Showmessage('Дата начала периуда отчёта не может быть больше даты окончания периуда отчёта!');
  end;
end;
 
procedure TForm_Ot.Bt_tabClick(Sender: TObject);
begin
  dm1.top:=Form_Ot.Top;
  dm1.left:=Form_Ot.Left;
  dm1.widith:=Form_Ot.Width;
  dm1.height:=Form_Ot.Height;
  Form_tab.Show;
  Form_tab.FormCreate(Form_tab);
  Form_Ot.Hide;
end;
 
procedure TForm_Ot.E_poisk_otClick(Sender: TObject);
begin
 E_poisk_ot.Clear;
end;
 
procedure TForm_Ot.E_poisk_otExit(Sender: TObject);
begin
  E_poisk_ot.Text:= 'Поиск';
end;
 
procedure TForm_Ot.E_poisk_otKeyUp(Sender: TObject; var Key: Word;
  Shift: TShiftState);
var i,j:integer;
begin
    i:=1;
    For j:=0 To ASG_Ot.RowCount-1 Do begin
      if AnsiPos(AnsiUpperCase(E_poisk_ot.Text), AnsiUpperCase(ASG_Ot.Cells[i,j]))>0 then begin
        ASG_Ot.Row:=j;
        ASG_Ot.Col:=i;
        Exit;
      end;
    end;
end;
 
procedure TForm_Ot.FormActivate(Sender: TObject);
begin
  if dm1.sostpr_ot=0 then begin
    Bt_clear_ot.Visible:=false;
    dm1.sostpr_ot:=1;
  end;
    if dm1.excel_sost_visible=0 then
      AdvPB_excel.Visible:=false
    else
      AdvPB_excel.Visible:=true;
end;
 
procedure TForm_Ot.FormClose(Sender: TObject; var Action: TCloseAction);
begin
  Application.Terminate;
end;
 
procedure TForm_Ot.FormCreate(Sender: TObject);
begin
try
  AdvDTP_ot_data1.Date:=dm1.datatabel;
  AdvDTP_ot_data2.Date:=dm1.datatabel;
  if (AdvCB_ot_org.Items.Count=0) then begin
      MyQuery_ot_spr.Active := false;            // Заполнение комбобокс организация  из бд
      MyQuery_ot_spr.SQL.Clear;
      MyQuery_ot_spr.SQL.Add('SELECT DISTINCT name1 FROM g_spr WHERE ((I4=1) AND (cod=101) AND (del!=1))');
      MyQuery_ot_spr.Active:=true;
    with MyQuery_ot_spr do
      begin
        MyQuery_ot_spr.DisableControls;
          AdvCB_ot_org.Items.BeginUpdate;
            MyQuery_ot_spr.First;
              while not MyQuery_ot_spr.Eof do
                begin
                  AdvCB_ot_org.Items.Add(MyQuery_ot_spr.FieldByName('name1').AsString);
                  MyQuery_ot_spr.Next;
                  end;
              AdvCB_ot_org.Items.EndUpdate;
            MyQuery_ot_spr.EnableControls;
      end;
      AdvCB_ot_org.ItemIndex:=0;
  end;
  except
    if Application.Active=false then begin
      if MessageDlg('Ошибка обновления выпадающих списков "ТАБЕЛЬ"! Программа будет закрыта! Пожалуйста обратитесь к администратору!',mtError, [mbOk], 0) = mrOk then begin
        Close;
      end;
    end;
  end;
end;
 
procedure TForm_Ot.FormShow(Sender: TObject);
var ini:TIniFile;
    i:integer;
    ctrl: TControl;
begin
     Form_Ot.WindowState:=wsNormal;
     Form_Ot.Width:=dm1.widith;
     Form_Ot.Height:=dm1.height;
     Form_Ot.Top:=dm1.top;
     Form_Ot.Left:=dm1.left;
      if FileExists(ExtractFilePath(paramstr(0))+'i.ini') then  begin  // если существует выбираем информацию
        ini:=TIniFile.Create(ExtractFilePath(paramstr(0))+'i.ini');
        for i := 0 to Form_Ot.ComponentCount-1 do
        if Form_Ot.Components[i] is TControl then
        (TMyControl(Form_Ot.Components[i])).Font.Size := ini.ReadInteger('Form_font','form_font_size',Form_Ot.Font.Size);
         ASG_Ot.FixedFont.Size:=ini.ReadInteger('Form_font','form_font_size',Form_Ot.Font.Size);
         ASG_Ot.GridLineColor:=ini.ReadInteger('ASG','linecolor',ASG_Ot.GridLineColor);
         ASG_Ot.GridFixedLineColor:=ini.ReadInteger('ASG','linecolor',ASG_Ot.GridFixedLineColor);
        ini.Free;
      end;
end;
 
procedure TForm_Ot.Timer1Timer(Sender: TObject);
begin
 Form_Ot.StatusBar1.Panels[0].text:=DateToStr(now);
 Form_Ot.StatusBar1.Panels[1].text:=TimeToStr(now);
end;
 
function TForm_Ot.ObnovASG_Ot;
var i,i1,j,rc1,st,h,hnorm,ks,k,row,cod,time4,time5,colkty,kty1,kty2:integer;
    id,obj,time,s,s1,s2,s3,sobj,s02,s12,s22,s32,passtime,time12,time22,time32,time42,time52,tzap:string;
    ob:boolean;
    a,b,sum,a1,b1,sum1,a2,b2,sum2,a3,b3,sum3,kty,time1,time2,time3:double;
    a02,b02,sum02,a12,b12,sum12:double;
    a22,b22,sum22,a32,b32,sum32:double;
begin
  try
  ASG_Ot.ClearAll;
  ASG_Ot.Cells[0,4]:='№';
  ASG_Ot.MergeCells(1,0,6,2);
  ASG_Ot.Cells[1,0]:='<FONT><P align="center"><B>Сотрудник</B></P></FONT>';
  ASG_Ot.Cells[1,2]:='ФИО';
  ASG_Ot.Cells[2,2]:='Таб. №';
  ASG_Ot.Cells[3,2]:='Должность';
  ASG_Ot.Cells[4,2]:='Отдел';
  ASG_Ot.Cells[5,2]:='Организация';
  ASG_Ot.Cells[6,2]:='Разряд';
  ASG_Ot.MergeCells(7,0,11,1);
  ASG_Ot.Cells[7,0]:='<FONT><P align="center">Отчёт занятости по обьектам и часам</P></FONT>';
  ASG_Ot.MergeCells(7,1,1,2);
  ASG_Ot.Cells[7,1]:='<FONT><P align="center">№<br>Объекта</P></FONT>';
  ASG_Ot.MergeCells(8,1,5,1);
  ASG_Ot.Cells[8,1]:='<FONT><P align="center">Часы</P></FONT>';
  ASG_Ot.Cells[8,2]:='Без<br>переработки';
  ASG_Ot.Cells[9,2]:='1,5';
  ASG_Ot.Cells[10,2]:='2';
  ASG_Ot.Cells[11,2]:='Другое';
  ASG_Ot.Cells[12,2]:='Выходные<br>/праздничные';
  ASG_Ot.MergeCells(13,1,5,1);
  ASG_Ot.Cells[13,1]:='<FONT><P align="center">Итого часов</P></FONT>';
  ASG_Ot.Cells[13,2]:='Без<br>переработки';
  ASG_Ot.Cells[14,2]:='1,5';
  ASG_Ot.Cells[15,2]:='2';
  ASG_Ot.Cells[16,2]:='Другое';
  ASG_Ot.Cells[17,2]:='Выходные<br>/праздничные';
  ASG_Ot.MergeCells(18,0,5,1);
  ASG_Ot.Cells[18,0]:='<FONT><P align="center">Кол-во неявок</P></FONT>';
  ASG_Ot.MergeCells(18,1,3,1);
  ASG_Ot.Cells[18,1]:='<FONT><P align="center">Дни</P></FONT>';
  ASG_Ot.MergeCells(21,1,2,1);
  ASG_Ot.Cells[21,1]:='<FONT><P align="center">Часы</P></FONT>';
  ASG_Ot.Cells[18,2]:='Отпуск<br>очередной/<br>ученический.';
  ASG_Ot.Cells[19,2]:='Больничный';
  ASG_Ot.Cells[20,2]:='Командировка';
  ASG_Ot.Cells[21,2]:='Без<br>сохранения';
  ASG_Ot.Cells[22,2]:='Без<br>ув.причины';
  ASG_Ot.MergeCells(23,0,1,3);
  ASG_Ot.Cells[23,0]:='Итого<br>КТУ';
    MyQuery_ot_ok.Active := false;
    MyQuery_ot_ok.SQL.Clear;
    MyQuery_ot_ok.SQL.Add('SELECT Q.id,US.name,Q.tabnom,D.name1,O.name1,G.name1,Q.raz,');
    MyQuery_ot_ok.SQL.Add('(SELECT COUNT(WT.dt_zap) FROM q_ywt WT WHERE (WT.dt_zap BETWEEN');
    MyQuery_ot_ok.SQL.Add('DATE("'+FormatDateTime('yyyy-mm-dd 00:00:00',AdvDTP_ot_data1.Date)+'")');
    MyQuery_ot_ok.SQL.Add('AND DATE("'+FormatDateTime('yyyy-mm-dd 23:59:59',AdvDTP_ot_data2.Date)+'"))');
    MyQuery_ot_ok.SQL.Add('AND (WT.user_id =(SELECT OK.id_user FROM q_ok OK WHERE (OK.id=Q.id) AND(OK.del<>1)))AND (WT.del<>1))tzap');
    MyQuery_ot_ok.SQL.Add('FROM q_ok Q,g_spr D,srv_users US,g_spr O,g_spr G');
    MyQuery_ot_ok.SQL.Add('WHERE (Q.id_user=US.id)AND(Q.id_dol=D.id)AND(Q.id_otdel=O.id)AND(Q.data2="3000-12-31 23:59:59")');
    MyQuery_ot_ok.SQL.Add('AND(Q.id_org=G.id)AND(G.name1="'+AdvCB_ot_org.Text+'")');
    MyQuery_ot_ok.SQL.Add('AND(Q.tipdoc=0)AND(Q.del!=1)');
    MyQuery_ot_ok.Active:=true;
    if MyQuery_ot_ok.RecordCount>0 then ASG_Ot.RowCount:=MyQuery_ot_ok.RecordCount+3;
    i:=1;
    while not MyQuery_ot_ok.Eof do begin
      inc(i);
      ASG_Ot.cells[0, i+1]:=MyQuery_ot_ok.fields[0].asString;
      ASG_Ot.cells[1, i+1]:=MyQuery_ot_ok.fields[1].asString;
      ASG_Ot.cells[2, i+1]:=MyQuery_ot_ok.Fields[2].asString;
      ASG_Ot.cells[3, i+1]:=MyQuery_ot_ok.fields[3].asString;
      ASG_Ot.cells[4, i+1]:=MyQuery_ot_ok.fields[4].asString;
      ASG_Ot.cells[5, i+1]:=MyQuery_ot_ok.fields[5].asString;
      ASG_Ot.cells[6, i+1]:=MyQuery_ot_ok.fields[6].asString;
      if (MyQuery_ot_ok.fields[6].AsInteger=0) then ASG_Ot.Cells[6,i+1]:='';
      id:=ASG_Ot.Cells[0,i+1];
      tzap:=MyQuery_ot_ok.FieldByName('tzap').AsString;
        if tzap<>'' then begin
        //if pos('0',tzap)=1 then delete(time,1,1);
        time32:=tzap;//FloatToStrF(((int(strtofloat(tzap))+(frac(strtofloat(tzap)) * 0.6))/24),ffFixed,3,0);
        if time32='0' then time32:='';
        end else time32:='';
      MyQuery_ot_buf.Active:= false;
      MyQuery_ot_buf.SQL.Clear;
      MyQuery_ot_buf.SQL.Add('SELECT BU.obj,BU.t1,BU.idOk,BU.id,(SELECT SD.st FROM q_sd SD WHERE (BU.data1=SD.stdata)AND(SD.del<>1))st,');
      MyQuery_ot_buf.SQL.Add('BU.cod,TIMESTAMPDIFF(HOUR,BU.data1,BU.data2)passtime,kty');
      MyQuery_ot_buf.SQL.Add('FROM  q_buf BU');
      MyQuery_ot_buf.SQL.Add('WHERE ((BU.idOK='+id+')');
      MyQuery_ot_buf.SQL.Add('AND(BU.cod<>0)AND(BU.cod<>9)AND(BU.cod<>8)AND(BU.cod<>100)');
      MyQuery_ot_buf.SQL.Add('AND(BU.data1 BETWEEN DATE("'+FormatDateTime('yyyy-mm-dd 00:00:00',AdvDTP_ot_data1.Date)+'")');
      MyQuery_ot_buf.SQL.Add('AND DATE("'+FormatDateTime('yyyy-mm-dd 23:59:59',AdvDTP_ot_data2.Date)+'"))');
      MyQuery_ot_buf.SQL.Add('AND(BU.data2 BETWEEN DATE("'+FormatDateTime('yyyy-mm-dd 00:00:00',AdvDTP_ot_data1.Date)+'")');
      MyQuery_ot_buf.SQL.Add('AND DATE("'+FormatDateTime('yyyy-mm-dd 23:59:59',AdvDTP_ot_data2.Date)+'"))');
      MyQuery_ot_buf.SQL.Add('AND(BU.del<>1))');
      MyQuery_ot_buf.Active:= true;
      obj:='';
      time:='';
      colkty:=0;
      kty:=0;
      kty1:=0;
      kty2:=0;
      time1:=0;
      time2:=0;
      time3:=0;
      time4:=0;
      time5:=0;
      time12:='';
      time22:='';
      time42:='';
      time52:='';
      rc1:=0;
      s:='';
      s1:='';
      s2:='';
      s3:='';
      hnorm:=8;
      sobj:='';
          while not MyQuery_ot_buf.Eof do begin
              passtime:=MyQuery_ot_buf.FieldByName('passtime').AsString;
              cod:=MyQuery_ot_buf.FieldByName('cod').AsInteger;
            case cod of
               200: begin
                 inc(rc1);
                 inc(i);
                 inc(colkty);
                 obj:= MyQuery_ot_buf.FieldByName('obj').AsString;
                 time:=FormatDateTime('hh:mm',MyQuery_ot_buf.FieldByName('t1').AsDateTime);
                 st:=MyQuery_ot_buf.FieldByName('st').AsInteger;
                 kty1:=MyQuery_ot_buf.FieldByName('kty').AsInteger;
                 if not (AnsiPos(AnsiUpperCase(obj), AnsiUpperCase(sobj))>0) then begin
                   ASG_Ot.cells[7,i]:=obj; // если нет обьекта добавляем
                   ASG_Ot.cells[0,i]:=MyQuery_ot_buf.FieldByName('idOk').AsString;
                   ASG_Ot.RowCount:=ASG_Ot.RowCount+1;
                   sobj:=sobj+obj+',';
                   ob:=true;
                 end
                 else begin
                   ob:=false;
                   i:=i-1;
                   rc1:=rc1-1;
                 end;
                 case st of  // статус дня
                    0:begin  // будни
                      h:=HourOf(strtodatetime(time));
                        if h>hnorm+2 then begin       // больше 10ч
                          if ob=true then begin ASG_Ot.cells[10,i]:=StringReplace(time, ',', ':',[rfReplaceAll, rfIgnoreCase]) end;
                          if ob=false then begin
                            For i1:=0 To ASG_Ot.RowCount-1 Do begin
                              if (AnsiPos(AnsiUpperCase(obj),AnsiUpperCase(ASG_Ot.Cells[7,i1]))>0)
                              AND(AnsiPos(AnsiUpperCase(MyQuery_ot_buf.FieldByName('idOk').AsString),AnsiUpperCase(ASG_Ot.Cells[0,i1]))>0) then begin
                                s02:=ASG_Ot.cells[10,i1];
                                if (time<>'') then begin   // если совпадают обьекты время суммируется
                                if s02='' then s02:='00';
                                s02:=StringReplace(s02, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                  if pos('0',s02)=1 then begin
                                  delete(s02,1,1);
                                  end;
                                  if pos('0',time)=1 then begin
                                  delete(time,1,1);
                                  end;
                                a32:=int(StrToFloat(s02))+(frac(StrToFloat(s02))/0.6);
                                b32:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                                sum32:=a32+b32;
                                sum32:=int(sum32)+(frac(sum32) * 0.6);
                                end;
                                ASG_Ot.cells[10,i1]:=StringReplace(floattostr(SimpleRoundTo(sum32,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                              end;
                            end;
                          end;
                          if (time<>'') then begin        // всего часов переработки х2
                          if s='' then s:='00';
                          s:=StringReplace(s, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                          time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                            if pos('0',s)=1 then begin
                            delete(s,1,1);
                            end;
                            if pos('0',time)=1 then begin
                            delete(time,1,1);
                            end;
                          a3:=int(StrToFloat(s))+(frac(StrToFloat(s))/0.6);
                          b3:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                          sum3:=a3+b3;
                          sum3:=int(sum3)+(frac(sum3) * 0.6);
                          end;
                          if sum3<>0 then s:=StringReplace(FloatToStr(SimpleRoundTo(sum3,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                        end
                        else
                        if h>hnorm  then begin       // больше 8ч
                        if ob=true then begin ASG_Ot.cells[9,i]:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]) end;
                          if ob=false then begin
                            For i1:=0 To ASG_Ot.RowCount-1 Do begin
                              if (AnsiPos(AnsiUpperCase(obj), AnsiUpperCase(ASG_Ot.Cells[7,i1]))>0)
                              AND(AnsiPos(AnsiUpperCase(MyQuery_ot_buf.FieldByName('idOk').AsString),AnsiUpperCase(ASG_Ot.Cells[0,i1]))>0) then begin
                                s12:=ASG_Ot.cells[9,i1];
                                if (time<>'') then begin   // если совпадают обьекты время суммируется
                                if s12='' then s12:='00';
                                s12:=StringReplace(s12, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                  if pos('0',s12)=1 then begin
                                  delete(s12,1,1);
                                  end;
                                  if pos('0',time)=1 then begin
                                  delete(time,1,1);
                                  end;
                                a22:=int(StrToFloat(s12))+(frac(StrToFloat(s12))/0.6);
                                b22:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                                sum22:=a22+b22;
                                sum22:=int(sum22)+(frac(sum22) * 0.6);
                                end;
                                ASG_Ot.cells[9,i1]:=StringReplace(floattostr(SimpleRoundTo(sum22,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                              end;
                            end;
                          end;
                          if (time<>'') then begin   // всего часов переработки х1.5
                          if s1='' then s1:='00';
                          s1:=StringReplace(s1, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                          time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                            if pos('0',s1)=1 then begin
                            delete(s1,1,1);
                            end;
                            if pos('0',time)=1 then begin
                            delete(time,1,1);
                            end;
                          a2:=int(StrToFloat(s1))+(frac(StrToFloat(s1))/0.6);
                          b2:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                          sum2:=a2+b2;
                          sum2:=int(sum2)+(frac(sum2) * 0.6);
                          end;
                          if sum2<>0 then s1:=StringReplace(FloatToStr(SimpleRoundTo(sum2,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                        end
                        else
                        if h<=hnorm then begin         // меньше равно 8ч
                        if ob=true then begin ASG_Ot.cells[8,i]:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]) end;
                          if ob=false then begin
                            For i1:=0 To ASG_Ot.RowCount-1 Do begin
                              if (AnsiPos(AnsiUpperCase(obj), AnsiUpperCase(ASG_Ot.Cells[7,i1]))>0)
1
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
20.06.2019, 22:20
Ответы с готовыми решениями:

Ошибка в работе функции "ЕСЛИ" EXCEL 2010
Добрый день. Господа, столкнулся с косяком в работе EXEL 2010 следующего характера. Разница...

Delphi и excel 2010
здраствуйте, при работе с экселем очень низкая скорость записи значений например код ...

Тормоз в работе Delphi+Excel
Делаю следующее: var Excel : Variant; begin Excel:= CreateOleObject('Excel.Application');...

Ошибка доступа при работе нового потока с формой
Доброго времени суток, дорогие форумчане! Помогите устранить проблему: при запуске потока, который...

8
1 / 1 / 0
Регистрация: 30.06.2018
Сообщений: 9
20.06.2019, 22:21  [ТС] 2
Delphi
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
AND(AnsiPos(AnsiUpperCase(MyQuery_ot_buf.FieldByName('idOk').AsString),AnsiUpperCase(ASG_Ot.Cells[0,i1]))>0) then begin
                                s22:=ASG_Ot.cells[8,i1];
                                if (time<>'') then begin   // если совпадают обьекты время суммируется
                                if s22='' then s22:='00';
                                s22:=StringReplace(s22, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                  if pos('0',s22)=1 then begin
                                  delete(s22,1,1);
                                  end;
                                  if pos('0',time)=1 then begin
                                  delete(time,1,1);
                                  end;
                                a12:=int(StrToFloat(s22))+(frac(StrToFloat(s22))/0.6);
                                b12:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                                sum12:=a12+b12;
                                sum12:=int(sum12)+(frac(sum12) * 0.6);
                                end;
                                ASG_Ot.cells[8,i1]:=StringReplace(floattostr(SimpleRoundTo(sum12,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                              end;
                            end;
                          end;
                          if (time<>'') then begin   // всего часов без переработки
                          if s2='' then s2:='00';
                          s2:=StringReplace(s2, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                          time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                            if pos('0',s2)=1 then begin
                            delete(s2,1,1);
                            end;
                            if pos('0',time)=1 then begin
                            delete(time,1,1);
                            end;
                          a1:=int(StrToFloat(s2))+(frac(StrToFloat(s2))/0.6);
                          b1:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                          sum1:=a1+b1;
                          sum1:=int(sum1)+(frac(sum1) * 0.6);
                          end;
                          if sum1<>0 then  s2:=StringReplace(FloatToStr(SimpleRoundTo(sum1,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                        end
                      end;
                    1:begin   // выходной/празд.
                      if ob=true then begin ASG_Ot.cells[12,i]:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]) end;
                          if ob=false then begin
                            For i1:=0 To ASG_Ot.RowCount-1 Do begin
                              if (AnsiPos(AnsiUpperCase(obj), AnsiUpperCase(ASG_Ot.Cells[7,i1]))>0)
                              AND(AnsiPos(AnsiUpperCase(MyQuery_ot_buf.FieldByName('idOk').AsString),AnsiUpperCase(ASG_Ot.Cells[0,i1]))>0) then begin
                                s32:=ASG_Ot.cells[12,i1];
                                if (time<>'') then begin   // если совпадают обьекты время суммируется
                                if s32='' then s32:='00';
                                s32:=StringReplace(s32, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                                  if pos('0',s32)=1 then begin
                                  delete(s32,1,1);
                                  end;
                                  if pos('0',time)=1 then begin
                                  delete(time,1,1);
                                  end;
                                a02:=int(StrToFloat(s32))+(frac(StrToFloat(s32))/0.6);
                                b02:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                                sum02:=a02+b02;
                                sum02:=int(sum02)+(frac(sum02) * 0.6);
                                end;
                                ASG_Ot.cells[12,i1]:=StringReplace(floattostr(SimpleRoundTo(sum02,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                              end;
                            end;
                          end;
                        if (time<>'') then begin   // всего выходных праздничных часов
                        if s3='' then s3:='00';
                        s3:=StringReplace(s3, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                        time:=StringReplace(time, ':', ',',[rfReplaceAll, rfIgnoreCase]);
                          if pos('0',s3)=1 then begin
                          delete(s3,1,1);
                          end;
                          if pos('0',time)=1 then begin
                          delete(time,1,1);
                          end;
                        a:=int(StrToFloat(s3))+(frac(StrToFloat(s3))/0.6);
                        b:=int(StrToFloat(time))+(frac(StrToFloat(time))/0.6);
                        sum:=a+b;
                        sum:=int(sum)+(frac(sum) * 0.6);
                        end;
                        if sum<>0 then  s3:=StringReplace(FloatToStr(SimpleRoundTo(sum,-2)), ':', ',',[rfReplaceAll, rfIgnoreCase]);
                      end;
                 end;
                 kty2:=kty2+kty1;
                 kty:=kty2/colkty;
               end;
               3,4:begin
               time1:=(time1+strtoint(passtime))/24;
               if int(time1)=0 then time12:='' else time12:=FloatToStrF(time1,ffFixed,3,0);
               end;
               2:begin
               time2:=(time2+strtoint(passtime))/24;
               if int(time2)=0 then time22:='' else time22:=FloatToStrF(time2,ffFixed,3,0);
               end;
               {7:begin
               time3:=(time3+strtoint(passtime))/24;
               if time3=0 then time32:='' else time32:=FloatToStrF(time3,ffFixed,3,0);
               end;}
               5:begin
               time4:=time4+strtoint(passtime);
               if int(time4)=0 then time42:='' else time42:=inttostr(time4);
               end;
               6:begin
               time5:=time5+strtoint(passtime);
               if int(time5)=0 then time52:='' else time52:=inttostr(time5);
               end;
            end;
          MyQuery_ot_buf.Next;
          end;
          ASG_Ot.cells[15,i-rc1+1]:=s;
          ASG_Ot.cells[14,i-rc1+1]:=s1;
          ASG_Ot.cells[13,i-rc1+1]:=s2;
          ASG_Ot.cells[17,i-rc1+1]:=s3;
          ASG_Ot.cells[18,i-rc1+1]:=time12;
          ASG_Ot.cells[19,i-rc1+1]:=time22;
          ASG_Ot.cells[20,i-rc1+1]:=time32;
          ASG_Ot.cells[21,i-rc1+1]:=time42;
          ASG_Ot.cells[22,i-rc1+1]:=time52;
          if (kty<>0) AND (kty>0) then ASG_Ot.cells[23,i-rc1+1]:=FloatToStrF(kty,ffFixed,3,2) else ASG_Ot.cells[23,i-rc1+1]:='';
        ASG_Ot.MergeCells(1,i-rc1+1,1,rc1+1); //Обьединяем ячейки
        ASG_Ot.MergeCells(2,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(3,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(4,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(5,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(6,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(13,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(14,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(15,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(16,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(17,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(18,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(19,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(20,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(21,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(22,i-rc1+1,1,rc1+1);
        ASG_Ot.MergeCells(23,i-rc1+1,1,rc1+1);
    MyQuery_ot_ok.next;
    end;
  except
      if MessageDlg('Ошибка обновления записей "ОТЧЁТ"! Программа будет закрыта! Пожалуйста обратитесь к администратору!',mtError, [mbOk], 0) = mrOk then begin
      Close;
      end;
  end;
  ASG_Ot.AutoSizeColumns(true);
  if ASG_Ot.ColWidths[3]>200 then ASG_Ot.ColWidths[3]:=200;
  if ASG_Ot.ColWidths[4]>200 then ASG_Ot.ColWidths[4]:=200;
  ASG_Ot.AutoSizeRows(true);
  ASG_Ot.ColWidths[0]:=-1;
end;
 
function TMyThread.FiltrStr;
 var s1,s2:string;
begin
 s1:=StringReplace(S,'<br>', ' ',[rfReplaceAll, rfIgnoreCase]);
 s2:=StringReplace(s1,'<FONT>', ' ',[rfReplaceAll, rfIgnoreCase]);
 s1:=StringReplace(s2,'</FONT>', ' ',[rfReplaceAll, rfIgnoreCase]);
 s2:=StringReplace(s1,'<P align="center">', ' ',[rfReplaceAll, rfIgnoreCase]);
 s1:=StringReplace(s2,'</P>', ' ',[rfReplaceAll, rfIgnoreCase]);
 s2:=StringReplace(s1,'</B>', ' ',[rfReplaceAll, rfIgnoreCase]);
 s1:=StringReplace(s2,'<B>', ' ',[rfReplaceAll, rfIgnoreCase]);
 Result:=s1;
end;
 
procedure TMyThread.Excel_v;
var i01,kol,ii2: integer;
    DestRange, WBk: OleVariant;
    Excel: Variant;
    str0,str1,str2,str3,str4,str5,str6,str7,str8,str9,str10,str11,str12:string;
    str13,str14,str15,str16,str17,str18,str19,str20,str21,str22,str23,s_povt,s_povt_buf:string;
begin
 try
    dm1.excel_sost_visible:=1;
    Form_Ot.Bt_exel.Visible:=false;
    Form_Ot.Bt_clear_ot.Visible:=false;
    Form_Ot.AdvPB_excel.Visible:=true;
    ii2:=0;
    Form_Ot.AdvPB_excel.Max:=Form_Ot.ASG_Ot.RowCount;
    Form_Ot.AdvPB_excel.Min:=0;
    Form_Ot.AdvPB_excel.Position:=ii2;
    Form_Ot.AdvPB_excel.Update;
    OleInitialize(nil);
    Excel := CreateOleObject('Excel.Application');
    Excel.DisplayAlerts:=False;
  WBk := Excel.WorkBooks.Add; // создаём новый документ
  For i01:=1 to Form_Ot.ASG_Ot.RowCount+1 do // Заполняеем Excel данными
    Begin
      Form_Ot.AdvPB_excel.Position:=ii2;
      Form_Ot.AdvPB_excel.Update;
      inc(ii2);
      str0:= Form_Ot.ASG_Ot.Cells[0,i01-1];
      str1:= Form_Ot.ASG_Ot.Cells[1,i01-1];
      str2:= Form_Ot.ASG_Ot.Cells[2,i01-1];
      str3:= Form_Ot.ASG_Ot.Cells[3,i01-1];
      str4:= Form_Ot.ASG_Ot.Cells[4,i01-1];
      str5:= Form_Ot.ASG_Ot.Cells[5,i01-1];
      str6:= Form_Ot.ASG_Ot.Cells[6,i01-1];
      str7:= Form_Ot.ASG_Ot.Cells[7,i01-1];
      str8:= Form_Ot.ASG_Ot.Cells[8,i01-1];
      str9:= Form_Ot.ASG_Ot.Cells[9,i01-1];
      str10:= Form_Ot.ASG_Ot.Cells[10,i01-1];
      str11:= Form_Ot.ASG_Ot.Cells[11,i01-1];
      str12:= Form_Ot.ASG_Ot.Cells[12,i01-1];
      str13:= Form_Ot.ASG_Ot.Cells[13,i01-1];
      str14:= Form_Ot.ASG_Ot.Cells[14,i01-1];
      str15:= Form_Ot.ASG_Ot.Cells[15,i01-1];
      str16:= Form_Ot.ASG_Ot.Cells[16,i01-1];
      str17:= Form_Ot.ASG_Ot.Cells[17,i01-1];
      str18:= Form_Ot.ASG_Ot.Cells[18,i01-1];
      str19:= Form_Ot.ASG_Ot.Cells[19,i01-1];
      str20:= Form_Ot.ASG_Ot.Cells[20,i01-1];
      str21:= Form_Ot.ASG_Ot.Cells[21,i01-1];
      str22:= Form_Ot.ASG_Ot.Cells[22,i01-1];
      str23:= Form_Ot.ASG_Ot.Cells[23,i01-1];
      kol:=0;
       if i01>3 then begin
        if str0='' then begin
        inc(kol);
          str0:= '';
          str1:= '';
          str2:= '';
          str3:= '';
          str4:= '';
          str5:= '';
          str6:= '';
          str7:= '';
          str8:= '';
          str9:= '';
          str10:= '';
          str11:= '';
          str12:= '';
          str13:= '';
          str14:= '';
          str15:= '';
          str16:= '';
          str17:= '';
          str18:= '';
          str19:= '';
          str20:= '';
          str21:= '';
          str22:= '';
          str23:= '';
        end;
      end;
      if pos(str0,s_povt)=0 then begin
        inc(kol);
        s_povt:=str0;
        s_povt_buf:= s_povt_buf+','+str0;
      end
      else begin
        if pos(str0,s_povt_buf)<>0  then begin
          inc(kol);
          str1:='';
          str2:= '';
          str3:= '';
          str4:= '';
          str5:= '';
          str6:= '';
          str13:= '';
          str14:= '';
          str15:= '';
          str16:= '';
          str17:= '';
          str18:= '';
          str19:= '';
          str20:= '';
          str21:= '';
          str22:= '';
          str23:= '';
        end else begin
          Excel.ExcelWorksheet.Rows.Delete;
        end;
        Excel.Range[Excel.Cells[i01-1,1],  Excel.Cells[i01+kol,1]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,2], Excel.Cells[i01+kol,2]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,3], Excel.Cells[i01+kol,3]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,4], Excel.Cells[i01+kol,4]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,5], Excel.Cells[i01+kol,5]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,6], Excel.Cells[i01+kol,6]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,13], Excel.Cells[i01+kol,13]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,14], Excel.Cells[i01+kol,14]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,15], Excel.Cells[i01+kol,15]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,16], Excel.Cells[i01+kol,16]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,17], Excel.Cells[i01+kol,17]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,18], Excel.Cells[i01+kol,18]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,19], Excel.Cells[i01+kol,19]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,20], Excel.Cells[i01+kol,20]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,21], Excel.Cells[i01+kol,21]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,22], Excel.Cells[i01+kol,22]].Select;
        Excel.Selection.MergeCells:=True;
         Excel.Range[Excel.Cells[i01-1,23], Excel.Cells[i01+kol,23]].Select;
        Excel.Selection.MergeCells:=True;
      end;
      Excel.ActiveSheet.Cells[i01, 1] := FiltrStr(str1);
      Excel.ActiveSheet.Cells[i01, 2] := FiltrStr(str2);
      Excel.ActiveSheet.Cells[i01, 3] := FiltrStr(str3);
      Excel.ActiveSheet.Cells[i01, 4] := FiltrStr(str4);
      Excel.ActiveSheet.Cells[i01, 5] := FiltrStr(str5);
      Excel.ActiveSheet.Cells[i01, 6] := FiltrStr(str6);
      Excel.ActiveSheet.Cells[i01, 7] := FiltrStr(str7);
      Excel.ActiveSheet.Cells[i01, 8] := FiltrStr(str8);
      Excel.ActiveSheet.Cells[i01, 9] := FiltrStr(str9);
      Excel.ActiveSheet.Cells[i01, 10] := FiltrStr(str10);
      Excel.ActiveSheet.Cells[i01, 11] := FiltrStr(str11);
      Excel.ActiveSheet.Cells[i01, 12] := FiltrStr(str12);
      Excel.ActiveSheet.Cells[i01, 13] := FiltrStr(str13);
      Excel.ActiveSheet.Cells[i01, 14] := FiltrStr(str14);
      Excel.ActiveSheet.Cells[i01, 15] := FiltrStr(str15);
      Excel.ActiveSheet.Cells[i01, 16] := FiltrStr(str16);
      Excel.ActiveSheet.Cells[i01, 17] := FiltrStr(str17);
      Excel.ActiveSheet.Cells[i01, 18] := FiltrStr(str18);
      Excel.ActiveSheet.Cells[i01, 19] := FiltrStr(str19);
      Excel.ActiveSheet.Cells[i01, 20] := FiltrStr(str20);
      Excel.ActiveSheet.Cells[i01, 21] := FiltrStr(str21);
      Excel.ActiveSheet.Cells[i01, 22] := FiltrStr(str22);
      Excel.ActiveSheet.Cells[i01, 23] := FiltrStr(str23);
    end;
    Excel.Range[Excel.Cells[3,7], Excel.Cells[3,23]].Select;
    Excel.Selection.Orientation:=90;
    Excel.Range[Excel.Cells[3,6], Excel.Cells[3,6]].Select;
    Excel.Selection.Orientation:=90;
    Excel.Range[Excel.Cells[2,7], Excel.Cells[3,7]].Select;
    Excel.Selection.Orientation:=90;
    Excel.Range[Excel.Cells[1,23], Excel.Cells[3,23]].Select;
    Excel.Selection.Orientation:=90;
    Excel.Range[Excel.Cells[1,1], Excel.Cells[2,6]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[1,7], Excel.Cells[1,17]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[1,18], Excel.Cells[1,22]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[2,7], Excel.Cells[3,7]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[2,8], Excel.Cells[2,12]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[2,13], Excel.Cells[2,17]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[2,18], Excel.Cells[2,20]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[2,21], Excel.Cells[2,22]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[1,23], Excel.Cells[3,23]].Select;
    Excel.Selection.MergeCells:=True;
    Excel.Selection.HorizontalAlignment:=3;
    Excel.Range[Excel.Cells[1,1], Excel.Cells[3,23]].Select;
    Excel.Range['A1:W3'].Font.Bold := True;  // Жирный шрифт
    Excel.Range[Excel.Cells[1,1], Excel.Cells[Form_Ot.ASG_Ot.RowCount,23]].Select;
    Excel.Selection.Borders.LineStyle:=1;
    Excel.Range[Excel.Cells[4,1], Excel.Cells[Form_Ot.ASG_Ot.RowCount,6]].Select;
    Excel.Selection.WrapText:=true;
    Excel.Worksheets[1].Name := 'Отчёт';
    Excel.Columns.AutoFit;
    Excel.Range[Excel.Cells[1,1], Excel.Cells[Form_Ot.ASG_Ot.RowCount,1]].Select;
    Excel.Selection.Columns.ColumnWidth := 15;
    Excel.Range[Excel.Cells[2,1], Excel.Cells[Form_Ot.ASG_Ot.RowCount,5]].Select;
    Excel.Selection.Columns.ColumnWidth := 20;
    Excel.Range[Excel.Cells[3,6], Excel.Cells[Form_Ot.ASG_Ot.RowCount,6]].Select;
    Excel.Selection.Columns.ColumnWidth := 3;
    Excel.Range[Excel.Cells[3,2], Excel.Cells[Form_Ot.ASG_Ot.RowCount,2]].Select;
    Excel.Selection.Columns.ColumnWidth := 8;
    Excel.Range[Excel.Cells[3,4], Excel.Cells[Form_Ot.ASG_Ot.RowCount,4]].Select;
    Excel.Selection.Columns.ColumnWidth := 10;
    Excel.Rows.AutoFit;
    s_povt_buf:='';
    Excel.Visible := True;
    OleUnInitialize;
    Form_Ot.Bt_exel.Visible:=true;
    Form_Ot.Bt_clear_ot.Visible:=true;
    Form_Ot.AdvPB_excel.Visible:=false;
    dm1.excel_sost_visible:=0;
  except
    if MessageDlg('Ошибка экспорта EXCEL! Экспорт прерван! Пожалуйста обратитесь к администратору!',mtError, [mbOk], 0) = mrOk then begin
      MyThread.Terminate;
      Excel.ActiveWorkbook.Close;
      Excel.Application.Quit;
    end;
  end;
end;
 
end.
0
884 / 404 / 174
Регистрация: 20.10.2016
Сообщений: 1,828
21.06.2019, 09:13 3
Цитата Сообщение от Fles_123 Посмотреть сообщение
разрабатываю приложение на Delphi 10.1
Делфи 10.1 и 2010 - это как Windows 10 и Windows XP соответственно.

Цитата Сообщение от Fles_123 Посмотреть сообщение
Подскажите где я мог ошибиться.
Не люблю это слово, но везде:

Цитата Сообщение от Fles_123 Посмотреть сообщение
Delphi
1
2
3
4
5
6
procedure TMyThread.Execute;
begin
* *MyThread.Excel_v;
* *{MyThread.Terminate;
* *MyThread.Free; *}
end;
Что это? Обращение к внешней переменной из потока просто так? Это в корне неверно. Верно так:
Delphi
1
2
3
4
5
6
procedure TMyThread.Execute;
begin
* *Excel_v;
* *{MyThread.Terminate;
* *MyThread.Free; *}
end;
И еще вопрос: где у вас инициализируется MyThread? Нигде? Ура, у вас AV.

Далее:
Delphi
1
newPotokExcel.Priority:=tpIdle;
За такое надо бить по рукам. Объясните, в чем смысл этой строки? Сделать так, чтобы ваш поток не работал вообще, потому что ему не выделяется процессорное время? Ура, вы добились своей цели. Не трогайте приоритет! Вообще не трогайте, пока не сможете ответить на вопрос "Зачем?" и на вопрос "Как работает приоритет потоков?".

Цитата Сообщение от Fles_123 Посмотреть сообщение
Delphi
1
Showmessage('Дата начала периуда отчёта не может быть больше даты окончания периуда отчёта!');
Слово "период" пишется через "о"

Далее. Самый смак. Поясните, пожалуйста, как вы так смело из
Delphi
1
procedure TMyThread.Excel_v;
обращаетесь напрямую к форме? Это первое и главнейшее табу работы с потоками, за такое древние индейцы майа приносили программистов в жертву богу синхронизации потоков. А самое интересное, что если то же самое сделать правильно - то есть через синхронизацию с основным потоком - то смысл дополнительного потока теряется.

Вердикт: не заморачивайтесь пока что с потоками.
0
1 / 1 / 0
Регистрация: 30.06.2018
Сообщений: 9
21.06.2019, 09:36  [ТС] 4
К великому сожалению, без доп. потока не обойтись. Т.к. если делать выгрузку в основном потоке то форма становиться не доступной для пользователя т.к. обработка данных отбирает все ресурсы. Что касается про обращение из потока к VCL в интернете полно примеров (с эмитировал). С процедурой synchronize не срослось.

Не могли бы вы скинуть 100% рабочий пример с использованием потока?
0
5394 / 4322 / 1060
Регистрация: 29.08.2013
Сообщений: 27,128
Записей в блоге: 3
21.06.2019, 10:06 5
вот тут
Обработать в программе зависание при выполнении SQL запросов
есть отличный архив

вроде понятно и наглядно
0
884 / 404 / 174
Регистрация: 20.10.2016
Сообщений: 1,828
21.06.2019, 10:11 6
Цитата Сообщение от Fles_123 Посмотреть сообщение
К великому сожалению, без доп. потока не обойтись. Т.к. если делать выгрузку в основном потоке то форма становиться не доступной для пользователя т.к. обработка данных отбирает все ресурсы. Что касается про обращение из потока к VCL в интернете полно примеров (с эмитировал). С процедурой synchronize не срослось.
Обойтись. Пусть ждут, значит.

Чтобы поток работал у вас в поток должна перейти вся логика: запрос и экспорт в excel, а с формы вам надо только забрать стартовые данные. И никак иначе. А у вас вся логика, фактически, находится на форме. При таком подходе никакой поток вас не спасет. Плюс, я подозреваю, что в интернете не сложно найти компоненты для экспорта из Dataset в Excel. Это значительно упростит вашу задачу.
1
5394 / 4322 / 1060
Регистрация: 29.08.2013
Сообщений: 27,128
Записей в блоге: 3
21.06.2019, 10:27 7
Цитата Сообщение от Nanotentacle Посмотреть сообщение
для экспорта из Dataset в Excel
все равно будет висеть - сначала на выполнении запроса, потом на экспорте в эксель

проще найти какой нибудь универсальный "отправитель в поток"

Цитата Сообщение от Nanotentacle Посмотреть сообщение
в поток должна перейти вся логика: запрос и экспорт в excel, а с формы вам надо только забрать стартовые данные.
+100500
1
884 / 404 / 174
Регистрация: 20.10.2016
Сообщений: 1,828
21.06.2019, 11:05 8
Цитата Сообщение от qwertehok Посмотреть сообщение
все равно будет висеть - сначала на выполнении запроса, потом на экспорте в эксель
Пусть висит. Если нет возможности сделать нормально через поток, то пусть висит. Это всегда лучше, чем неработающее приложение.
0
1 / 1 / 0
Регистрация: 30.06.2018
Сообщений: 9
31.10.2019, 22:57  [ТС] 9
Извёлся но сделал в потоке, нужно было просто все данные в динамический массив запихнуть при формировании таблицы. Всем спасибо за ответы.
0
31.10.2019, 22:57
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
31.10.2019, 22:57
Помогаю со студенческими работами здесь

Клиент-сервер: Если запустить первый поток то он работает, при запуске второго потока выходит ошибка
Здравствуйте, пытаюсь разбить код на два потока. 1) Поток прием клиентов. void login_server()...

Отчет из программы на Delphi в win7 excel 2010 увеличивает строки
Добрый день, подскажите в чем может быть проблема? Формирую отчет из программы написанной на...

Странные изменения в работе VBA Excel 2010 под Windows 7 SP1 по сравнению с Windows XP
Добрый день. Сложилась следующая странная сутуация: В течение года пользуюсь макросом Excel...

Ошибка в работе с Excel
Вводит при чтении с excel файла: Warning: strtotime(): It is not safe to rely on the system's...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
9
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru