Delphi Excel Control Method
1. Create an Excel file
To control Excel in Delphi, OLE Automation is required. Ole2 is generally used to create an OLE object. When an OLE object is activated, the server program is only activated within the container program. This is called in-place activation ).
When creating an Excel file, create an OLE object and then create a worksheet in the object, as shown in the createexcel function:
Function createexcel: variant; VaR V: variant; Sheet: variant; Begin V: = createoleobject ('excel. application'); // create an OLE object V. Visible: = true; V. workbooks. Add (-4167); // Add a worksheet V. workbooks [1]. Sheets [1]. Name: = 'test '; Sheet: = V. workbooks [1]. Sheets ['test']; Return V; End; |
2. Data Table Control
Excel table control mainly includes data import and modification, cell merge and border control, and table copy and paste. When the report format is certain, it is particularly important to copy and paste tables. In this way, you can create a file template and then output multiple pages of reports as needed.
(1) import data (importdata)
Procedure importdata; VaR I, J: integer; V: variant; Begin V: = createexcel; // create an Excel file test For I: = 0 to maxcolumn do Begin For J: = 0 to maxrow do V. workbooks [1]. Sheets [1]. cells [I, j]: = I * j; // import data End; End; |
(2) cell merging and border control (linestylecontrol)
Cells are merged when the merging range is selected. Border control allows you to check whether border lines are displayed. Other control methods can follow the process below.
Procedure linestylecontrol; VaR V, sheet, range: variant; Begin V: = createexecl; Sheet: = V. workbooks [1]. Sheets [1]; Range: = sheet. Range [sheet. cells [], sheet. cells []; // select a table Range. Select; Range. merge; // merge cells. Range. Borders. linestyle: = xlcontinuous; // set the border to visible. Range. Font. Size: = 9; // change the text font size in the table. End; |
(3) copy and paste a table (copyandpaste)
Procedure copyandpaste; VaR V, sheet, range: variant; Begin V: = createexecl; Sheet: = V. workbooks [1]. Sheets [1]; Range: = sheet. Range [sheet. cells [], sheet. cells []; Range. Select; // select the table to be copied Range. Copy; // copy the selected table. Sheet. Range [sheet. cells [], sheet. cells []. Select; // select the position to paste Sheet. paste; // paste the table End; |
3. Save the file
File storage is based on the creation of files. The SaveFile process describes the issues that should be paid attention to during file storage:
Procedure SaveFile; VaR Sheet, V: variant; Begin V: = createexcel; If savedialog.exe cute then Begin V. workbooks [1]. saveas (savedialog. filename); // save the file V. workbooks [1]. Close; // close the worksheet V. Quit; // close Excel V: = unassigned; End; End; |