Консультация № 192572
17.02.2018, 09:50
0.00 руб.
1 9 1
Уважаемые эксперты! Пожалуйста, ответьте на вопрос:Необходимо считать таблицу зависимости некоторого коэффициента k от параметров А и Б, которая находится в Word в StringGrid в несколько изменённом виде (см. приложенный файл). Делаю следующим образом.


Помогите организовать цикл считывания?

Приложение:
uses
ComObj;

procedure TForm1.Button1Click(Sender: TObject);
var
wdApp, wdDocs, wdDoc1, wdTable1 : Variant;
i, j, Row, Col : Integer;
S : String;
Od : TOpenDialog;
Sg : TStringGrid;
begin
Od := OpenDialog1;
Sg := StringGrid1;

if Od.InitialDir = '' then
Od.InitialDir := ExtractFilePath( Application.ExeName );
if not Od.Execute then Exit;
if not FileExists(Od.FileName) then begin
MessageDlg(
'Файл с именем:'#10 + Od.FileName + #10'Не найден. Действие отменено.'
, mtWarning, [mbOk], 0
);
Exit;
end;
//Попытка запустить и подключиться к MS Word.
try
wdApp := CreateOleObject('Word.Application');
except
MessageDlg(
'Не удалось подключиться к MS Word. Действие отменено.'
, mtWarning, [mbOk], 0);
Exit;
end;

//Делаем видимым окно MS Word.
wdApp.Visible := True;
//Ссылка на коллекцию документов.
wdDocs := wdApp.Documents;
//Попытка открыть выбранный файл.
wdDoc1 := wdDocs.Open(FileName:=Od.FileName);
//Проверка - есть ли в документе таблицы.
if wdDoc1.Tables.Count = 0 then begin
//wdApp.Quit;
ShowMessage('В документе нет таблиц. Действие отменено.');
Exit;
end;
//Ссылка на первую таблицу.
wdTable1 := wdDoc1.Tables.Item(1);
Прикрепленные файлы:
cae5bedc5e6c96d17591559e9bcac391f664689d.jpg

Обсуждение

давно
Старший Модератор
31795
6196
19.02.2018, 12:47
общий
Адресаты:
1) Задание расплывчатое, ну есть таблица, слегка измененная, и что? Прочитайте, это как эксперт портала(не автор вопроса), который пытается понять, что спрашивающий хочет.
2) Проект - выложите.
3) Word-файл - выложите.
Цитата: Правила портала
Ограничения на размер дискового пространства, времени хранения файлов и стоимость услуги "Мои файлы"(кнопка в левой колонке)

1-й класс 40 Мб 6 мес. бесплатно
Об авторе:
Мне безразлично, что Вы думаете о обо мне, но я рад за Вас - Вы начали думать.

давно
Посетитель
400264
21
19.02.2018, 19:21
общий
Первая таблица - это таблица из word, вторая это как она должна выглядеть в StringGrid. В приложенном файле ещё одна попытка объяснить проблему.
Прикрепленные файлы:
6ee5684fab452cf32e0387cffffac023.rar
давно
Старший Модератор
31795
6196
20.02.2018, 11:57
общий
20.02.2018, 12:32
Адресаты:

[code lang=pascal] //Close MS Word.
wdApp.Quit;

StringGrid2.ColCount := 3;
StringGrid2.RowCount := (Sg1.RowCount-1)*(Sg1.ColCount-1)+1;

StringGrid2.Cells[0, 0] := 'A';
StringGrid2.Cells[1, 0] := 'B';
StringGrid2.Cells[2, 0] := 'k';
i:=1;
for Col:=1 to Sg1.ColCount-1 do
begin
for Row :=1 to Sg1.RowCount-1 do
begin
StringGrid2.Cells[0,i]:=Sg1.Cells[0,Row];
StringGrid2.Cells[1,i]:=Sg1.Cells[Col,0];
StringGrid2.Cells[2,i]:=Sg1.Cells[Col,Row];
inc(i);
end;
end;[/code]
Об авторе:
Мне безразлично, что Вы думаете о обо мне, но я рад за Вас - Вы начали думать.

давно
Старший Модератор
31795
6196
20.02.2018, 15:01
общий
Адресаты:
Цитата: 08101967
Помогите организовать цикл считывания?

Подошло?
Об авторе:
Мне безразлично, что Вы думаете о обо мне, но я рад за Вас - Вы начали думать.

давно
Посетитель
400264
21
20.02.2018, 17:53
общий
Да, то что надо, только как это сразу в StringGrid2 считывать из Word без предварительной загрузки в StringGrid1
давно
Старший Модератор
31795
6196
20.02.2018, 18:32
общий
Адресаты:
[code lang=pascal] StringGrid2.ColCount := 3;
StringGrid2.RowCount := (wdTable1.Columns.Count-1)*(wdTable1.Rows.Count-1)+1;

StringGrid2.Cells[0, 0] := 'A';
StringGrid2.Cells[1, 0] := 'Â';
StringGrid2.Cells[2, 0] := 'k';
i:=1;
for Col:=1 to wdTable1.Columns.Count-1 do
begin
for Row :=1 to wdTable1.Rows.Count-1 do
begin
StringGrid2.Cells[0,i]:= s1(wdTable1.Cell(Row+1,1).Range.Text);
StringGrid2.Cells[1,i]:= s1(wdTable1.Cell(1, Col+1).Range.Text);
StringGrid2.Cells[2,i]:= s1(wdTable1.Cell(Row+1, Col+1).Range.Text);
inc(i);
end;[/code]

[code lang=pascal]function s1(a:string):string;
begin
delete(a,length(a)-1,2);
s1:=a;
end;[/code]
Об авторе:
Мне безразлично, что Вы думаете о обо мне, но я рад за Вас - Вы начали думать.

давно
Старший Модератор
31795
6196
20.02.2018, 18:44
общий
Адресаты:
Вы об этом?
Об авторе:
Мне безразлично, что Вы думаете о обо мне, но я рад за Вас - Вы начали думать.

давно
Посетитель
400264
21
20.02.2018, 18:45
общий
Всё работает! Большое спасибо!
давно
Старший Модератор
31795
6196
20.02.2018, 18:50
общий
это ответ
Здравствуйте, 08101967!

Доработанный проект:
[code lang=pascal h=350]unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, Menus, ComObj, ExtCtrls, StdCtrls;

type
TForm1 = class(TForm)
MainMenu1: TMainMenu;
N1: TMenuItem;
N2: TMenuItem;
OpenDialog1: TOpenDialog;
GroupBox1: TGroupBox;
Splitter1: TSplitter;
StringGrid1: TStringGrid;
GroupBox2: TGroupBox;
StringGrid2: TStringGrid;
procedure N2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}
function s1(a:string):string;
begin
delete(a,length(a)-1,2);
s1:=a;
end;
procedure TForm1.N2Click(Sender: TObject);
var
wdApp, wdDocs, wdDoc1, wdTable1: Variant;
i, j, Row, Col: Integer;
S: string;
Od: TOpenDialog;
Sg1: TStringGrid;
begin
Od := OpenDialog1;
Sg1 := StringGrid1;
// StringGrid2 := StringGrid1;
if Od.InitialDir = '' then
Od.InitialDir := ExtractFilePath(Application.ExeName);
if not Od.Execute then Exit;
if not FileExists(Od.FileName) then
begin
MessageDlg(
'Файл с именем:'#10 + Od.FileName + #10'Не найден. Действие отменено.'
, mtWarning, [mbOk], 0);
Exit;
end;
//Попытка запустить и подключиться к MS Word.
try
wdApp := CreateOleObject('Word.Application');
except
MessageDlg(
'Не удалось подключиться к MS Word. Действие отменено.'
, mtWarning, [mbOk], 0
);
Exit;
end;
//Делаем видимым окно MS Word.
wdApp.Visible := false; //True;
//Ссылка на коллекцию документов.
wdDocs := wdApp.Documents;
//Попытка открыть выбранный файл.
wdDoc1 := wdDocs.Open(FileName := Od.FileName, ReadOnly := True);
//Проверка - есть ли в документе таблицы.
if wdDoc1.Tables.Count = 0 then
begin
//wdApp.Quit;
ShowMessage('В документе нет таблиц. Действие отменено.');
Exit;
end;
//Ссылка на первую таблицу.
wdTable1 := wdDoc1.Tables.Item(1);

//Заполняем StringGrid1
Sg1.ColCount := wdTable1.Columns.Count; // +Sg.FixedCols;
Sg1.RowCount := wdTable1.Rows.Count; //+Sg.FixedRows;
i := 0;
for Row := 1 to wdTable1.Rows.Count do
begin
j := 0;
for Col := 1 to wdTable1.Columns.Count do
begin
S := wdTable1.Cell(Row, Col).Range.Text;
//Удаление конечных символов #13#10.
Delete(S, Length(S) - 1, 2);
Sg1.Cells[j, i] := S;
Inc(j);
end;
Inc(i);
end;

//Заполняем StringGrid2
StringGrid2.ColCount := 3;
StringGrid2.RowCount := (wdTable1.Columns.Count-1)*(wdTable1.Rows.Count-1)+1;

StringGrid2.Cells[0, 0] := 'A';
StringGrid2.Cells[1, 0] := 'В';
StringGrid2.Cells[2, 0] := 'k';
i:=1;
for Col:=1 to wdTable1.Columns.Count-1 do
begin
for Row :=1 to wdTable1.Rows.Count-1 do
begin
StringGrid2.Cells[0,i]:= s1(wdTable1.Cell(Row+1,1).Range.Text);
StringGrid2.Cells[1,i]:= s1(wdTable1.Cell(1, Col+1).Range.Text);
StringGrid2.Cells[2,i]:= s1(wdTable1.Cell(Row+1, Col+1).Range.Text);
inc(i);
end;
end;

//Закрываем MS Word.
wdApp.Quit;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
StringGrid2.Cells[0, 0] := 'A';
StringGrid2.Cells[1, 0] := 'В';
StringGrid2.Cells[2, 0] := 'k';

StringGrid2.Cells[0, 1] := 'A1';
StringGrid2.Cells[1, 1] := 'В1';
StringGrid2.Cells[2, 1] := 'k1,1';

StringGrid2.Cells[0, 2] := 'A2';
StringGrid2.Cells[1, 2] := 'В1';
StringGrid2.Cells[2, 2] := 'k1,2';

StringGrid2.Cells[0, 3] := 'A3';
StringGrid2.Cells[1, 3] := 'В1';
StringGrid2.Cells[2, 3] := 'k1,3';

StringGrid2.Cells[0, 4] := 'A1';
StringGrid2.Cells[1, 4] := 'В2';
StringGrid2.Cells[2, 4] := 'k2,1';

StringGrid2.Cells[0, 5] := 'A2';
StringGrid2.Cells[1, 5] := 'В2';
StringGrid2.Cells[2, 5] := 'k2,2';

StringGrid2.Cells[0, 6] := 'A3';
StringGrid2.Cells[1, 6] := 'В2';
StringGrid2.Cells[2, 6] := 'k2,3';

StringGrid2.Cells[0, 7] := 'A1';
StringGrid2.Cells[1, 7] := 'В3';
StringGrid2.Cells[2, 7] := 'k3,1';

StringGrid2.Cells[0, 8] := 'A2';
StringGrid2.Cells[1, 8] := 'В3';
StringGrid2.Cells[2, 8] := 'k3,2';

StringGrid2.Cells[0, 9] := 'A3';
StringGrid2.Cells[1, 9] := 'В3';
StringGrid2.Cells[2, 9] := 'k3,3';

StringGrid2.Cells[0, 7] := 'A1';
StringGrid2.Cells[1, 7] := 'В4';
StringGrid2.Cells[2, 7] := 'k4,1';

StringGrid2.Cells[0, 8] := 'A2';
StringGrid2.Cells[1, 8] := 'В4';
StringGrid2.Cells[2, 8] := 'k4,2';

StringGrid2.Cells[0, 9] := 'A3';
StringGrid2.Cells[1, 9] := 'В4';
StringGrid2.Cells[2, 9] := 'k4,3';

StringGrid2.Cells[0, 10] := 'A1';
StringGrid2.Cells[1, 10] := 'В5';
StringGrid2.Cells[2, 10] := 'k5,1';

StringGrid2.Cells[0, 11] := 'A2';
StringGrid2.Cells[1, 11] := 'В5';
StringGrid2.Cells[2, 11] := 'k5,2';

StringGrid2.Cells[0, 12] := 'A3';
StringGrid2.Cells[1, 12] := 'В5';
StringGrid2.Cells[2, 12] := 'k5,3';
end;

end.[/code]
Удачи!
Об авторе:
Мне безразлично, что Вы думаете о обо мне, но я рад за Вас - Вы начали думать.

Форма ответа