How to save data in a Word file to the right place in Delphi?

I need to create an exam ticket for the program. To do this, I need to enter in a program written in Delphi, First Name, Last Name, Subject, Option, and Year, and that this is saved along with the answer options in the Word file in the places that I specified.

Is it possible to do this?

enter a description of the image here

Here is something like this should look like

enter a description of the image here

What other components are needed for this?

Author: Kromster, 2017-12-22

1 answers

Can. At the same time, I think you can do without third-party components.
The easiest way is to create a template for a future document, in which the text will already be placed in the right places. Then your task will only be to replace it with your own. Initialize OLEObject (of course, Word must be installed!):

var
  Word : variant;
<...>
     try
          Word := CreateOleObject('Word.Application');
     except
          MessageBox ('Не установлен Microsoft Word!!!', 'Ошибка',
                              MB_OK);
          exit;
     end;
     word.documents.open ('Путь к документу\Имя.docx'); // открываем ваш файл
     word.Visible := false; // спрячем его с экрана

If you do everything honestly, now you need to work with Word collections via Word.Documents.Item, i.e., for example, to access the 1st column of the last table (if you have there are tables in the document), you need to do this:

W1.ActiveDocument.Tables.Item(W1.ActiveDocument.Tables.Count).Columns.Item(1).Select;

I will immediately give you a hint: in order not to suffer with sorting through collections later, make this replacement with your hands once when recording the macro is enabled (Service/Macro/Start recording...), then you will know which collections to access.

Well, now a little "cheating".

  procedure FindAndReplace (ww:variant; SearchStr, ReplaceStr : string);
  begin
    ww.Selection.Find.Text := SearchStr;
    ww.Selection.Find.Replacement.Text := ReplaceStr;
    ww.Selection.Find.Execute (Replace := 2);
  end;
<...>
  FindAndReplace (Word, '%prepod%', edit1.Text); // просто ищем  в документе предопределенный текст и заменяем его.
  FindAndReplace (Word, '%bilet%', edit2.Text);
  FindAndReplace (Word, '%DATE%', edit3.Text);

There is a lot of information on working with Office documents on the Web, I recommend you to study it, you will discover a lot of useful things.

Well, if it's really lazy, here free component VectorSoft Report, which allows you to create a document you need on the basis of a ready-made template with a little effort.

 3
Author: Viktor Tomilov, 2017-12-22 05:17:31