excel - 将数据从 DBGrid 导出到 Excel

标签 excel delphi delphi-7 ado

我想知道是否有人有办法将数据从 DBGrid 导出到 Excel?我正在使用 Delphi 7 、 Excel 2007 和 ADO 。
任何帮助将不胜感激。

最佳答案

如果您想快速导出原始数据,只需使用类似的内容导出记录集(ADODataset.recordset)即可:

procedure ExportRecordsetToMSExcel(DestName: string; Data: _Recordset);
var
  ovExcelApp: OleVariant;
  ovExcelWorkbook: OleVariant;
  ovWS: OleVariant;
  ovRange: OleVariant;
begin
  ovExcelApp := CreateOleObject('Excel.Application'); //If Excel isnt installed will raise an exception
  try
    ovExcelWorkbook   := ovExcelApp.WorkBooks.Add;
    ovWS := ovExcelWorkbook.Worksheets.Item[1]; // go to first worksheet
    ovWS.Activate;
    ovWS.Select;
    ovRange := ovWS.Range['A1', 'A1']; //go to first cell
    ovRange.Resize[Data.RecordCount, Data.Fields.Count];
    ovRange.CopyFromRecordset(Data, Data.RecordCount, Data.Fields.Count); //this copy the entire recordset to the selected range in excel
    ovWS.SaveAs(DestName, 1, '', '', False, False);
  finally
    ovExcelWorkbook.Close(SaveChanges := False);
    ovWS := Unassigned;
    ovExcelWorkbook := Unassigned;
    ovExcelApp := Unassigned;
  end;
end;

关于excel - 将数据从 DBGrid 导出到 Excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17058563/

相关文章:

vba - 获取最后一个非空工作表的最佳方法

delphi - cxGrid - 检查记录的页脚摘要

delphi - 是否有 Exit 方法可以退出嵌套过程及其所有者过程?

Excel 用连续 x 轴绘制时间序列频率

excel - 根据屏幕分辨率调整工作表缩放级别

delphi - SAPI 与 Dephi : Async speech doesn't work

Delphi - 从外部文件执行函数和过程

delphi - 如何使编辑控件不接受 0 作为第一位数字?

excel - 在grails中实现excel导入的高效方法

multithreading - 处理 TThread.Execute 中的异常以使其不可中断