- uses DBGrids, ComObj, ActiveX, Variants;
- procedure ExportDBGridToExcel(F_DBGrid: TDBGrid; F_Title: string = '数据资料';
- F_ScreenUpdating: Boolean = true; F_PrintPreview: Boolean = False; F_AddChart: Boolean = False);
- const
- CLASS_ExcelApplication: TGUID = '{00024500-0000-0000-C000-000000000046}';
- var
- ExcelApp, Sheet, Chart: OleVariant;
- Unknown: IUnknown;
- Bm: TBookmarkStr;
- Col, Row: Integer;
- I: Integer;
- begin
- if (F_DBGrid.DataSource <> nil) and (F_DBGrid.DataSource.DataSet <> nil) then
- with F_DBGrid.DataSource.DataSet do
- begin
- if not active then exit;
- try
- if not Succeeded(GetActiveObject(CLASS_ExcelApplication, nil, Unknown)) then
- Unknown := CreateComObject(CLASS_ExcelApplication);
- except
- raise Exception.Create('不能启动 Microsoft Excel,请确认 Microsoft Excel 已正确安装在本机上');
- end;
- ExcelApp := Unknown as IDispatch;
- ExcelApp.Visible := True;
- ExcelApp.Workbooks.Add;
- if not F_ScreenUpdating then
- ExcelApp.ScreenUpdating := False;
- DisableControls;
- try
- Bm := Bookmark;
- First;
- Row := 3;
- Col := 1;
- for I := 0 to F_DBGrid.Columns.Count - 1 do
- begin
- if F_DBGrid.Columns[I].Visible then
- ExcelApp.Cells[Row, Col] := F_DBGrid.Columns[I].Title.Caption;
- Inc(Col);
- end;
- Inc(Row);
- while not EOF do
- begin
- Col := 1;
- for I := 0 to F_DBGrid.Columns.Count - 1 do
- begin
- if F_DBGrid.Columns[I].Visible then
- if F_DBGrid.Columns[I].Field <> nil then
- ExcelApp.Cells[Row, Col] := F_DBGrid.Columns[I].Field.DisplayText;
- Inc(Col);
- end;
- Inc(Row);
- Next;
- end;
- Col := 1;
- for I := 0 to F_DBGrid.Columns.Count - 1 do
- begin
- if F_DBGrid.Columns[I].Visible then
- ExcelApp.Columns[Col].AutoFit; ;
- Inc(Col);
- end;
- ExcelApp.Cells[1, 1] := F_Title;
- Bookmark := Bm;
- finally
- EnableControls;
- if not ExcelApp.ScreenUpdating then
- ExcelApp.ScreenUpdating := True;
- end;
- end;
- if F_AddChart then
- begin
- Sheet := ExcelApp.ActiveSheet;
- Sheet.Range[Sheet.Cells[4, 1], Sheet.Cells[Row - 1, Col - 1]].Select;
- Chart := ExcelApp.ActiveWorkbook.Charts.Add;
- Chart.SetSourceData(
- Sheet.Range[Sheet.Cells[4, 1], Sheet.Cells[Row - 1, Col - 1]], EmptyParam);
- Chart.Location(1, EmptyParam);
- end;
- if F_PrintPreview then
- ExcelApp.ActiveWorkbook.PrintPreview;
- end;
ExportDBGridToExcel
最新推荐文章于 2020-03-18 10:36:12 发布