For some code, refer to the post on the csdn website!
Procedure tform1.bitbtn1click (Sender: tobject );
VaR
Excelworksheet: texcelworksheet;
Excelapplication: texcelapplication;
Excelworkbook: texcelworkbook;
I, row, column: integer;
X1, x2, Y1, Y2: integer;
Begin
X1: = 1;
Y1: = 2;
Column: = 1;
Excelapplication: = texcelapplication. Create (application );
Excelworksheet: = texcelworksheet. Create (application );
Excelworkbook: = texcelworkbook. Create (application );
Try
Excelapplication. Connect;
Except
Showmessage ('error! ');
End;
Excelapplication. Visible [0]: = true;
Excelapplication. Caption: = 'excel application ';
Excelapplication. workbooks. Add (null, 0 );
Excelworkbook. connectto (excelapplication. workbooks [1]);
Excelworksheet. connectto (excelworkbook. worksheets [1] As _ worksheet );
Row: = 3;
Excelworksheet. cells. item [1, 1]: = 'xxxxx'; // set the title
Excelworksheet. Range [excelworksheet. cells. item [],
Excelworksheet. cells. item [1, 2]. Merge (0 );
Excelworksheet. cells. item [1, 1]. horizontalalignment: = xlcenter;
For I: = 1 to dbgrid1.columns. Count do
Begin
Excelworksheet. cells. item [2, I]: = dbgrid1.columns. items [I-1]. fieldname;
End;
While not (dbgrid1.datasource. dataset. EOF) Do
Begin
Column: = 1;
For I: = 1 to dbgrid1.columns. Count do
Begin
Excelworksheet. cells. item [row, column]: = dbgrid1.datasource. dataset. Fields [I-1]. asstring;
Column: = column + 1;
End;
Dbgrid1.datasource. dataset. Next;
Row: = row + 1;
End;
Y2: = row-1;
X2: = column-1;
// Data content settings
Excelworksheet. Range [excelworksheet. cells. item [Y1, X1],
Excelworksheet. cells. item [Y2, x2]. Font. Name: = 'body ';
Excelworksheet. Range [excelworksheet. cells. item [Y1, X1],
Excelworksheet. cells. item [Y2, x2]. Font. Size: = 10;
Excelworksheet. Range [excelworksheet. cells. item [y1-1, X1],
Excelworksheet. cells. item [Y2, x2]. Borders. Color: = clblack;
Excelworksheet. Range [excelworksheet. cells. item [y1-1, X1],
Excelworksheet. cells. item [Y2, x2]. Borders. linestyle: = xlcontinuous;
Excelworksheet. cells. item []. Font. Name: = ' '; // set the title Font.
Excelworksheet. cells. item [1, 1]. Font. Size: = 12;
Excelworksheet. cells. item [1, 1]. Font. Bold: = true;
Excelapplication. Disconnect;
Excelapplication. Free;
Excelworksheet. Free;
Excelworkbook. Free;
End;