.xls格式导出,uses中添加cxGridExportLink
代码如下:
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‘, UpperCase(SaveFileDialog.FileName)) <= 0 then 12 SaveFileDialog.FileName := SaveFileDialog.FileName + ‘.XLS‘; 13 ExportGridToExcel(SaveFileDialog.FileName, gridMain); 14 ShowMessage(‘数据已成功导出到您指定的目录中‘); 15 end; 16 Result := SaveFileDialog.FileName; 17 SaveFileDialog.Free; 18 end;
.csv格式导出,uses中添加cxGridExportLink
代码如下:
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格式无法通过cxGrid现有封装的方法实现,可以通过.xls/.csv格式转换成.xlsx格式。
代码如下:
1 procedure Saveto_xlsx(tn: string; fn: string); 2 var 3 ExcelApp, Excelbook, ExcelChart: OleVariant; 4 //tn:需要转换格式的源文件路径 5 //fn:转换之后的文件存储路径 6 begin 7 try 8 ExcelApp := CreateOleObject(‘Excel.Application‘); 9 ExcelApp.Visible := True;//False 10 ExcelApp.Caption := ‘应用程序调用 Microsoft Excel‘; 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;