Author: Igor Siticov
How to transfer data from Excel to Word?
Answer:
Below is demonstration how to perform this task.
Add these global variables:
1 XLApp: Variant;
2 WordApp: Variant;
3 4 Add these constants:
5 6 xlWBATWorksheet = -4167;
7 wdDoNotSaveChanges = 0;
8 9 //For creating data in Excel we shall start it first: 10 11 //Starting Excel application:12 XLApp := CreateOleObject('Excel.Application');
13 // Making it visible:14 XLApp.Visible := True;
15 // Adding workbook:16 XLApp.Workbooks.Add[XLWBatWorksheet];
17 // Specifying name of worksheet:18 XLApp.Workbooks[1].Worksheets[1].Name := 'Delphi Data';
19 20 //Now inserting data to Excel: 21 22 procedure TForm1.InsertData2Excel;
23 var24 Sheet: Variant;
25 i: Integer;
26 begin27 Sheet := XLApp.Workbooks[1].Worksheets['Delphi Data'];
28 for i := 1 to 10 do29 Sheet.Cells[i, 1] := i;
30 end;
And copying data from Excel to Word.
This process consists of two phrases:
Data should be copied from Excel into Windows clipboard.
Data should be pasted from Windows clipboard into the Word.
For successful completion both Excel and Word should be running.
Copying data from Excel into Windows clipboard:
31 procedure TForm1.CopyData;
32 var33 Sheets: Variant;
34 begin35 SetFocus;
36 37 Sheets := XLApp.Sheets;
38 // Selecting our worksheet:39 Sheets.Item['Delphi Data'].Activate;
40 // Selecting our cells:41 Sheets.Item['Delphi Data'].Range['A1:A10'].Select;
42 // Copying selected cells into clipboard:43 Sheets.Item['Delphi Data'].UsedRange.Copy;
44 // Inserting copied data into Word45 InserData2Word;
46 end;
47 48 procedure TForm1.InsertData2Word;
49 var50 Range: Variant;
51 i: Integer;
52 begin53 // Starting Word:54 WordApp := CreateOleObject('Word.Application');
55 // Making it visible:56 WordApp.Visible := True;
57 // Adding new document:58 WordApp.Documents.Add;
59 // Inserting description text into new document:60 Range := WordApp.Documents.Item(1).Range;
61 Range.Text := 'This is a column from a spreadsheet: ';
62 for i := 1 to 3 do63 WordApp.Documents.Item(1).Paragraphs.Add;
64 // Inserting data from clipboard65 Range :=
66 WordApp.Documents.Item(1).Range(WordApp.Documents.Item(1).Paragraphs.Item(3).Range.S
67 tart);
68 Range.Paste;
69 for i := 1 to 3 do70 WordApp.Documents.Item(1).Paragraphs.Add;
71 end;
Don't forget to close Excel and Word by your program termination:
72 procedure TForm1.FormDestroy(Sender: TObject);
73 begin74 ifnot VarIsEmpty(XLApp) then75 begin76 XLApp.DisplayAlerts := False; // Discard unsaved files....77 XLApp.Quit;
78 end;
79 80 ifnot VarIsEmpty(WordApp) then81 begin82 WordApp.Documents.Item(1).Close(wdDoNotSaveChanges);
83 WordApp.Quit;
84 end;
85 end;