Export .xls format, uses add cxGridExportLink
code show as below:
1 function SaveToExcel(gridMain: TcxGrid; FileName: string): string; 2 var 3 SaveFileDialog: TSaveDialog; 4 begin 5 //示例:SaveToExcel(dxDBGrid1,'默认文件名'); 6 SaveFileDialog := TSaveDialog.Create(nil); 7 SaveFileDialog.FileName := FileName; 8 SaveFileDialog.Filter := '*.xls'; 9 if SaveFileDialog.Execute then 10 begin 11 if pos(' .XLS ' , the UpperCase (SaveFileDialog.FileName)) <= 0 the then 12 is SaveFileDialog.FileName: + = SaveFileDialog.FileName ' .XLS ' ; 13 is ExportGridToExcel (SaveFileDialog.FileName, gridMain); 14 the ShowMessage ( ' data has been successfully exported to you specify the directory ' ); 15 End ; 16 the Result: = SaveFileDialog.FileName; . 17 SaveFileDialog.Free; 18 is End ;
Export .csv format, uses add cxGridExportLink
code show as below:
1 begin 2 Screen.Cursor := crSQLWait; 3 FileNameCache := FileName + FormatDateTime('YYYYMMDD', NOW); 4 FileName := FileNameCache + '.CSV'; 5 FilePathCache := 'C:/TMP/' + FileNameCache; 6 FilePath := FilePathCache + '.CSV'; 7 ExportGridToText(FilePathCache + '.XLS', cxGrid_M, True, True, ',', '', '', 'CSV'); 8 Screen.Cursor := crDefault; 9 end;
.xlsx format can not be achieved by conventional methods cxGrid package, it can be converted by .xls / .csv .xlsx format to format.
code show as below:
. 1 Procedure Saveto_xlsx (TN: String ; Fn: String ); 2 var . 3 ExcelApp, Excelbook, ExcelChart: OleVariant; . 4 // TN: need to convert the source file path format . 5 // Fn: file storage path after conversion . 6 the begin . 7 the try . 8 ExcelApp: = CreateOleObject ( ' the Excel.Application ' ); . 9 ExcelApp.Visible: = True; // False 10 ExcelApp.Caption: = ' application calls Excel the Microsoft ' ; . 11 ExcelApp.Application.DisplayAlerts := False; 12 ExcelApp.WorkBooks.Open(tn); 13 ExcelApp.ActiveWorkbook.SaveAs(fn, 51); 14 ExcelApp.Application.Quit; 15 ExcelApp.Application.DisplayAlerts := True; 16 Excelapp := Null; 17 except 18 Application.Messagebox('Excel 没有安装!', 'Hello', MB_ICONERROR + mb_Ok); 19 Abort; 20 end; 21 end;