delphi中TStringGrid数据的导出

没什么好说的,就是一个导出Excel的功能,代码如下:

function TExportToExcel.Export(SGrid_List: TStringGrid;filename:string;out Errstr:string): Boolean;
var
  excelapp:Variant;
  page:Variant;
  i,j:Integer;
  savedialog:TSaveDialog;
  strsavefile:string;
begin
  try
    result := false;
    savedialog := TSaveDialog.Create(self);
    try
      savedialog.FileName := filename;
      savedialog.Filter := '*.xls';
      if not savedialog.Execute() then
        exit;
      strsavefile := savedialog.FileName;
      Screen.Cursor:=crhourglass; //屏幕指针形状
      excelapp := CreateOleObject('excel.application');
      excelapp.workbooks.add;
      excelapp.workbooks[1].worksheets[1].name:=filename;
      page:=excelapp.workbooks[1].worksheets[filename];
      for i:= 0 to SGrid_List.RowCount-2 do
      begin
        //第一列没有数据,不用
        for j:=1 to SGrid_List.ColCount-1 do
        begin
          page.cells[i+1,j]:= SGrid_List.Cells[j,i];
        end;
      end;
      excelapp.activeworkbook.saveas(strsavefile);
      Application.ProcessMessages;
      excelapp.application.quit;
      result := true;
    finally
      savedialog.Free;
      Screen.Cursor:=crDefault;
    end;
  except
    on E:Exception do
    begin
      Errstr := e.Message;
      result := false;
    end;
  end;
end;

 

posted @ 2013-10-16 23:19  _倔强  阅读(698)  评论(0编辑  收藏  举报